home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Resources / Security / McAfee SiteAdvisor 26.6 / safe.xpi / chrome / safe.jar / content / framework.js < prev    next >
Text File  |  2008-03-11  |  85KB  |  2,810 lines

  1. /*-----------------------------------------------------
  2.   Copyright (c) 2006 McAfee, Inc.  All Rights Reserved.
  3.   -----------------------------------------------------*/
  4.  
  5. function SiteAdvisorFirefoxExtension() {
  6.  
  7. var premium;
  8. var on;
  9. var highliteon;
  10. var buttonon;
  11. var psurf;
  12. var suite;
  13. var uid;
  14. var uuid;
  15. var pagedom;
  16. var domain_specifier = "";
  17. var loc = "";
  18. var sloc = "";
  19. var prodmode = true;
  20. var siteadvisor_debug = false;
  21. var siteadvisor_release = true;
  22. var on_search_page = "false";
  23. var byebye = false;
  24. var completejavascript = false;
  25. var alreadyWarned = false;
  26. var udscache = new Array();
  27. var cachesize = 50;
  28. var cachettl = 43200000;
  29. var regexmap = new Array();
  30. var req;
  31. var doSSL = false;
  32. var searchdat = "search.dat";
  33. var mode;
  34. var BASIC = 1;
  35. var PLUS = 2;
  36. var CRIPPLED = 3;
  37. var McLocales = new Array("en-US","en-CA","en-GB","en-AU","en-IE","es-ES","es-MX","es-AR","es-CL","es-PE",
  38.                           "fr-FR","fr-CA","pt-PT","pt-BR","zh-CN","zh-TW","cs-CZ","de-DE","it-IT","ja-JP",
  39.                           "nl-NL","nb-NO","no-NO","pl-PL","da-DK","fi-FI","tr-TR","sv-SE","ko-KR","el-EL",
  40.                           "hu-HU","ru-RU","sk-SK");
  41. var OEMStrB;
  42. var overlay_objects = new Array();
  43. var highlite_colors = new Array();
  44. var whitelistedDomains = "";
  45.  
  46. function putContents(rURL,lURL,build,cksum){
  47.   var contents = getContentsFromURL(rURL);
  48.   if (!contents) return;
  49.   tFile = "temp.js";
  50.   writeFile(contents,tFile);
  51.   if (validateCksum(tFile,cksum))
  52.       copyFile(tFile,lURL);
  53.   else
  54.       return;
  55.   if (build != -1) {
  56.       setBuild(build);
  57.   }
  58. }
  59.  
  60. function copyFile(src,dst) {
  61.    str = readFile(src);
  62.    writeFile(str,dst);
  63. }
  64.  
  65. function getContentsFromURL(rURL) {
  66.    try {
  67.       httpreq = new XMLHttpRequest();
  68.       httpreq.open('GET', rURL, false);
  69.       httpreq.send(null);
  70.       if(httpreq.status == 200){
  71.          return httpreq.responseText;
  72.       }
  73.       else {
  74.          return null;
  75.       }
  76.    } catch (connerr) {
  77.       return null;
  78.    }
  79. }
  80.  
  81. function readFile(lURL) {
  82.   var file = Components.classes["@mozilla.org/file/directory_service;1"]
  83.                      .getService(Components.interfaces.nsIProperties)
  84.                      .get("ProfD", Components.interfaces.nsIFile);
  85.   file.append(lURL);
  86.   var data = "";
  87.   var fstream = Components.classes["@mozilla.org/network/file-input-stream;1"]
  88.                         .createInstance(Components.interfaces.nsIFileInputStream);
  89.   var sstream = Components.classes["@mozilla.org/scriptableinputstream;1"]
  90.                         .createInstance(Components.interfaces.nsIScriptableInputStream);
  91.   fstream.init(file, 1, 0, false);
  92.   sstream.init(fstream);
  93.   var str = sstream.read(-1);
  94.   while (str.length > 0) {
  95.     data += str;
  96.     str = sstream.read(-1);
  97.   }
  98.   sstream.close();
  99.   fstream.close();
  100.   return data;
  101. }
  102.  
  103. function writeFile(str,lURL) {
  104.   var file = Components.classes["@mozilla.org/file/directory_service;1"]
  105.                      .getService(Components.interfaces.nsIProperties)
  106.                      .get("ProfD", Components.interfaces.nsIFile);
  107.   file.append(lURL);
  108.   var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
  109.                          .createInstance(Components.interfaces.nsIFileOutputStream);
  110.   foStream.init(file, 0x02 | 0x08 | 0x20, 0664, 0); // write, create, truncate
  111.   foStream.write(str, str.length);
  112.   foStream.close();
  113. }
  114.  
  115. function getFirefoxVersion() {
  116.    var version = "0";
  117.  
  118.    try {
  119.       var appInfo = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULAppInfo);
  120.       version = appInfo.version;
  121.    } catch (appinfoerr) {
  122.       try {
  123.          version = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch).getCharPref("app.version");
  124.       } catch (preferr) {
  125.       }
  126.    }
  127.  
  128.    return version;
  129. }
  130.  
  131. function compareFirefoxVersion(compareVersion) {
  132.     var version = getFirefoxVersion();
  133.  
  134.     try {
  135.         var versionChecker = Components.classes["@mozilla.org/xpcom/version-comparator;1"].getService(Components.interfaces.nsIVersionComparator);
  136.         if(versionChecker.compare(version, compareVersion) < 0) return true;
  137.     } catch (vcheckerr) {
  138.     }
  139.  
  140.     return false;
  141. }
  142.  
  143. function validateCksum(lURL,cksum) {
  144.    var version = "0";
  145.    try {
  146.       var appInfo = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULAppInfo);
  147.       version = appInfo.version;
  148.    } catch (appinfoerr) {
  149.       try {
  150.      version = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch).getCharPref("app.version");
  151.       } catch (preferr) {
  152.      return true;
  153.       }
  154.    }
  155.    try {
  156.       var versionChecker = Components.classes["@mozilla.org/xpcom/version-comparator;1"].getService(Components.interfaces.nsIVersionComparator);
  157.       if(versionChecker.compare(version, "1.5") < 0) return true;
  158.    } catch (vcheckerr) {
  159.       return true;
  160.    }
  161.  
  162.    var file = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get("ProfD", Components.interfaces.nsIFile);
  163.    file.append(lURL);
  164.    var hasher = Components.classes["@mozilla.org/security/hash;1"].createInstance(Components.interfaces.nsICryptoHash);
  165.    hasher.init(hasher.MD5);
  166.    var fstream = Components.classes["@mozilla.org/network/file-input-stream;1"]
  167.                         .createInstance(Components.interfaces.nsIFileInputStream);
  168.    fstream.init(file, 1, 0, false);
  169.    hasher.updateFromStream(fstream,fstream.available());
  170.    if (hasher.finish(true) == base16To64(cksum))
  171.       return true;
  172.    if (cksum == "0123456789ABCDEF") return true;
  173.    return false;
  174. }
  175.  
  176. function base16To64(str16) {
  177.    var b64 = new Array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/');
  178.    var str64 = ""
  179.    while (str16.length > 0) {
  180.       str24 = str16.substring(0,6);
  181.       i24 = parseInt(str24,16);
  182.       if (str24.length == 6) {
  183.      str64 += b64[(i24&0xFC0000)>>18]+b64[(i24&0x3F000)>>12]+b64[(i24&0xFC0)>>6]+b64[i24&0x3F];
  184.       } else if (str24.length == 4) {
  185.      str64 += b64[(i24&0xFC00)>>10]+b64[(i24&0x3F0)>>4]+b64[(i24&0xF)<<2]+"=";
  186.       } else if (str24.length == 2) {
  187.      str64 += b64[(i24&0xFC)>>2]+b64[(i24&0x3)<<4] + "==";
  188.       }
  189.       str16 = str16.slice(6);
  190.    }
  191.    return str64;
  192. }
  193.  
  194. function addScript(lURL) {
  195.    try{
  196.       data = readFile(lURL);
  197.    } catch(e) {
  198.       return;
  199.    }
  200.  
  201.    try{
  202.       eval(data);
  203.    } catch(e) {}
  204.  
  205.    if (!completejavascript)
  206.       setBuild(0);
  207.  
  208.    if (getLKV() != 0 && parseFloat(getVersion()) > getLKV()) {
  209.     sendUpgradePing();
  210.     setLKV(getVersion());
  211.    } else if (getLKV() == 0) {
  212.         setLKV(getVersion());
  213.    }
  214.  
  215.    setUpdateURL();
  216.    populateMenus();
  217.  
  218.    var appcon = window.document.getElementById("appcontent");
  219.  
  220.    if (appcon) {
  221.         appcon.addEventListener("DOMContentLoaded", save_me, false);
  222.         appcon.addEventListener("focus",focus_handler,true);
  223.         appcon.addEventListener("blur",focus_handler,true);
  224.         appcon.addEventListener("mousedown",focus_handler,true);
  225.         appcon.addEventListener("mouseup",focus_handler,true);
  226.         appcon.addEventListener("load",load_handler,true);
  227.         appcon.addEventListener("click",saDontWarn,false);
  228.    }
  229.    
  230.    //****************************************************************************
  231.    
  232.     listObj = new Object();
  233.  
  234.     listObj.wpl = Components.interfaces.nsIWebProgressListener;
  235.     listObj.QueryInterface = function(aIID) 
  236.     {
  237.         if (aIID.equals(listObj.wpl) ||
  238.             aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
  239.             aIID.equals(Components.interfaces.nsISupports)) 
  240.         {
  241.             return this;
  242.         }
  243.         throw Components.results.NS_NOINTERFACE;
  244.     }
  245.  
  246. listObj.onStateChange = function(aProgress, aRequest, aFlag, aStatus) 
  247. {
  248.     if (aFlag & listObj.wpl.STATE_START) 
  249.     {
  250.         if (aRequest)
  251.         {
  252.             changebutton_URI(aRequest.originalURI);
  253.         }
  254.     }
  255.     return 0;
  256. }
  257.  
  258. //// This fires when the location bar changes i.e load event is confirmed
  259. //// or when the user switches tabs
  260. listObj.onLocationChange = function(aProgress, aRequest, aURI) { return 0; }
  261.  
  262. //// For definitions of the remaining functions see XulPlanet.com
  263. listObj.onProgressChange    = function() { return 0; };
  264. listObj.onStatusChange      = function() { return 0; };
  265.  
  266. listObj.onSecurityChange    = function() { return 0; };
  267. listObj.onLinkIconAvailable = function() { return 0; };
  268.  
  269.     try
  270.     {
  271.         var doc = document.getElementById("content");
  272.         if (doc)
  273.         {
  274.            doc.addProgressListener( listObj,  Components.interfaces.nsIWebProgress.NOTIFY_ALL );
  275.         }
  276.     }
  277.     catch(e)
  278.     {
  279.         //alert(e.message);
  280.     }
  281.  
  282.    
  283.    
  284.    //****************************************************************************
  285.    
  286.    
  287.    
  288.    
  289.    
  290.    
  291.    
  292.    
  293.    
  294.    
  295.    changebutton();
  296. }
  297.  
  298. function saDontWarn(e)
  299. {
  300.     if((e.originalTarget.tagName=="B" && e.originalTarget.parentNode.parentNode.id=="DontWarn") || (e.originalTarget.tagName=="SPAN" && e.originalTarget.parentNode.id=="DontWarn") && window._content.location.host.match(/\.siteadvisor\./))
  301.     {
  302.         try
  303.         {
  304.             psurf = getPsurfEnabled();
  305.             if(psurf)
  306.                 setPSurf(false);
  307.  
  308.             var l = window._content.location.href;
  309.             var dIdx = l.indexOf("domain=");
  310.             var sIdx = l.indexOf("&" , dIdx + 7);
  311.             if(sIdx < 0)
  312.                 sIdx = l.length
  313.             var url = l.slice(dIdx + 7, sIdx);
  314.             url = stripargs(url);
  315.     
  316.             var flag = getBoolPref("extensions.safe.flag");
  317.             if(!flag) return;
  318.             addWhitelist(url);
  319.             if(e.originalTarget.tagName=="B" && e.originalTarget.parentNode.parentNode.id=="DontWarn")
  320.                 e.originalTarget.parentNode.parentNode.href = "http://www." + url;
  321.             if(e.originalTarget.tagName=="SPAN" && e.originalTarget.parentNode.id=="DontWarn")
  322.                 e.originalTarget.parentNode.href = "http://www." + url;
  323.         }
  324.         catch(e)
  325.         {
  326.             //alert(e.message)
  327.         }
  328.     }
  329. }
  330.  
  331. function makeDssQuery(dssquery,loc) {
  332.     var dssurl = getDss();
  333.     httpGetRequest(dssurl, dssquery, true, true,null,false,loc);
  334. }
  335.  
  336. function makeSSLDssQuery(dssquery,loc) {
  337.         var dssurl = getDss();
  338.         httpGetRequest(dssurl, dssquery, true, true,null,true,loc);
  339. }
  340.  
  341. function retryDssQuery(dssurl,dssquery,greq,forceSSL,loc) {
  342.     if (dssurl.match(/dss1/)) dssurl = dssurl.replace("dss1","dss2");
  343.     else if (dssurl.match(/dss2/)) dssurl = dssurl.replace("dss2","dss1");
  344.     setDss(dssurl);
  345.     httpGetRequest(dssurl, dssquery, false, false,greq,forceSSL,loc);
  346. }
  347.  
  348. function useSSL(dssurl) {
  349.    if (dssurl.match(/^https:/)) return dssurl;
  350.    else return dssurl.replace(/^http:/,"https:");
  351. }
  352.  
  353. function httpGetRequest(dssurl,dssquery,retry,timeout,oldreq,forceSSL,loc) {
  354.     if (oldreq) {
  355.         if (oldreq.timeoutId) clearTimeout(oldreq.timeoutId);
  356.         oldreq.onreadystatechange = null;
  357.         oldreq.abort();
  358.     }
  359.     var greq = new XMLHttpRequest();
  360.     if (timeout) {
  361.         greq.timeoutId = setTimeout(retryDssQuery,10000,dssurl,dssquery,greq,forceSSL,loc);
  362.         greq.onprogress = function () {
  363.             clearTimeout(greq.timeoutId);
  364.             greq.timeoutId = setTimeout(retryDssQuery,10000,dssurl,dssquery,greq,forceSSL,loc);
  365.         }
  366.     }
  367.  
  368.     greq.open('GET',(forceSSL? useSSL(dssurl) : checkSSL(dssurl)) + dssquery, true);
  369.     greq.overrideMimeType('text/xml');
  370.     greq.setRequestHeader("Accept-Encoding", "");
  371.     greq.onreadystatechange = function () {
  372.         if (greq.readyState == 4) {
  373.             var stat;
  374.             try {stat = greq.status;}
  375.             catch(staterr) {stat = 500;}
  376.             if (greq.timeoutId) clearTimeout(greq.timeoutId);
  377.             if (stat == 200 && greq.responseXML.documentElement.nodeName != "parsererror") {
  378.                 DSSResponseHandler(greq.responseXML,dssquery,loc);
  379.             } else if (retry) {
  380.                 retryDssQuery(dssurl,dssquery,greq,forceSSL,loc);
  381.             } else {
  382.                 DSSFailureHandler(dssquery);
  383.             }
  384.         }
  385.     };
  386.     greq.send(null);
  387. }
  388.  
  389. function DSSResponseHandler(xml,dssquery,loc) {
  390.     var responseHandlers = {'PingResponse': versionHandler,
  391.                     'DomainQueryResponse': SingleQueryDSSHandler};
  392.         var handlerFound = false;
  393.     for (var key in responseHandlers)
  394.         if (xml.getElementsByTagName(key).length == 1) {
  395.             responseHandlers[key](xml,loc);
  396.                         handlerFound = true;
  397.         }
  398.         if (!handlerFound) {
  399.           checkForEmergency(xml);
  400.           DSSFailureHandler(dssquery);
  401.         }
  402. }
  403.  
  404. function DSSFailureHandler(dssquery) {
  405.     var responseHandlers = {'Ping?': pingFailureHandler,
  406.                     'Query?': function(){}};
  407.     for (var key in responseHandlers)
  408.         if (dssquery.indexOf(key) == 0)
  409.             responseHandlers[key]();
  410. }
  411. function pingFailureHandler() {
  412.     addScript(searchdat);
  413. }
  414.  
  415. function get_js() {
  416.     doSSL = getBoolPref("extensions.safe.doSSL",false);
  417.     makeSSLDssQuery("Ping?includeVersionInfo=true&version=2&client_ver=" + getFullVersion() +"&locale="+getLocale()+"&aff_id="+getAffid()+"&UID="+getGuid(), window._content.location.href);
  418. }
  419.  
  420. function versionHandler(XML,loc) {
  421.  
  422.     checkForEmergency(XML);
  423.  
  424.     var versioninfos = XML.getElementsByTagName("VersionInfo");
  425.  
  426.     for (var i = 0; i < versioninfos.length; i++) {
  427.         versioninfo = versioninfos.item(i);
  428.         entity = versioninfo.attributes.getNamedItem("entity").nodeValue;
  429.  
  430.         if (entity.toLowerCase() == searchdat) {
  431.             newestbuild = parseInt(versioninfo.attributes.getNamedItem("version").nodeValue);
  432.             currentbuild = getBuild();
  433.             var sdfile = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get("ProfD", Components.interfaces.nsIFile);
  434.             sdfile.append("search.dat");
  435.             if (newestbuild > currentbuild || !sdfile.exists()) {
  436.                 loca = versioninfo.attributes.getNamedItem("location").nodeValue;
  437.                     cksum = versioninfo.attributes.getNamedItem("cksum").nodeValue;
  438.                     var ioserv = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
  439.                     var locaObj = ioserv.newURI(loca,"utf-8",null);
  440.                 if (locaObj.host.match(/\.siteadvisor\.com$/) || locaObj.host.match(/\.mcafee\.com$/) || locaObj.host.match(/^siteadvisor\.com$/) || locaObj.host.match(/^mcafee\.com$/))
  441.                     putContents(loca,searchdat,newestbuild,cksum);
  442.                 if (currentbuild != 0 && getBuild() > currentbuild)
  443.                     sendUpgradePing();
  444.                 immediate = versioninfo.attributes.getNamedItem("immediate").nodeValue;
  445.                 if (immediate == "true")
  446.                     check_auto_update();
  447.             }
  448.  
  449.             break;
  450.         }
  451.     }
  452.     addScript(searchdat);
  453. }
  454.  
  455. function getShowMenuTellAFriend()
  456. {
  457.     try
  458.     {
  459.         var showMenuTellAFriend = OEMstrb("ShowMenuTellAFriend");
  460.         if (showMenuTellAFriend && showMenuTellAFriend.toLowerCase() == "true") return false;
  461.         else if (showMenuTellAFriend && showMenuTellAFriend.toLowerCase() == "false") return true;
  462.     }
  463.     catch (StrBErr) {}
  464.     
  465.     return false;
  466. }
  467.  
  468. function getShowMenuSendFeedback()
  469. {
  470.     try
  471.     {
  472.         var showMenuSendFeedback = OEMstrb("ShowMenuSendFeedback");
  473.         if (showMenuSendFeedback && showMenuSendFeedback.toLowerCase() == "true") return false;
  474.         else if (showMenuSendFeedback && showMenuSendFeedback.toLowerCase() == "false") return true;
  475.     }
  476.     catch (StrBErr) {}
  477.     
  478.     return false;
  479. }
  480.  
  481. function getSafeSearch()
  482. {
  483.     try
  484.     {
  485.         var SafeSearch = OEMstrb("SafeSearch");
  486.         if (SafeSearch && SafeSearch.toLowerCase() == "true") return true;
  487.         else if (SafeSearch && SafeSearch.toLowerCase() == "false") return false;
  488.     }
  489.     catch (StrBErr) {}
  490.     
  491.     return true;
  492. }
  493.  
  494. function populateMenus() {
  495.    if(mode==CRIPPLED)
  496.    {
  497.     setCrippled()
  498.     return;
  499.    }
  500.     buttonon = getButtonEnabled();
  501.     psurf = getPsurfEnabled();
  502.     premium = getPremium();
  503.     on = getSafeOn();
  504.     highliteon = getHighlight();
  505.     doSSL = getSSL();
  506.     suite = getSuite();
  507.     uid = getUID();
  508.  
  509.     if (!buttonon)
  510.         document.getElementById("SAFE-Combined-MoreInfo").setAttribute("disabled","true");
  511.     else
  512.         document.getElementById("SAFE-Combined-MoreInfo").setAttribute("disabled","false");
  513. //    document.getElementById("SAFE-Combined-MoreInfo").disabled = !buttonon;
  514.  
  515.     document.getElementById('SAFE-Combined-RegisterNow').collapsed = true;
  516.     
  517.     document.getElementById('SAFE-Combined-WhiteList').collapsed = premium && psurf;
  518.  
  519.     document.getElementById('SAFE-Combined-Enable').collapsed = buttonon || (premium && psurf);
  520.     document.getElementById('SAFE-Combined-Disable').collapsed = !buttonon || (premium && psurf);
  521.  
  522.     document.getElementById('SAFE-Combined-EnablePSurf').collapsed = (psurf || !premium);
  523.     document.getElementById('SAFE-Combined-DisablePSurf').collapsed = (!psurf || !premium);
  524.  
  525.     document.getElementById('SAFE-Combined-TellFriend').collapsed = getShowMenuTellAFriend();
  526.     document.getElementById('SAFE-Combined-SendFeedback').collapsed = getShowMenuSendFeedback();
  527.     if (getShowMenuUpsellMessage() && !premium) {
  528.         document.getElementById('SAFE-Combined-Upsell').collapsed = false;
  529.         document.getElementById('SAFE-Combined-Upsell').label = getMenuUpsellMessage();
  530.     } else {
  531.         document.getElementById('SAFE-Combined-Upsell').collapsed = true;
  532.     }
  533. }
  534.  
  535. function getBoolPref(prefname, prefdef) {
  536.     var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
  537.     try{
  538.         return pref.getBoolPref(prefname);
  539.     } catch(e) {
  540.         pref.setBoolPref(prefname, prefdef);
  541.         return pref.getBoolPref(prefname);
  542.     }
  543. }
  544.  
  545. function setBoolPref(prefname, prefvalue) {
  546.     var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
  547.     try{
  548.         pref.setBoolPref(prefname, prefvalue);
  549.     } catch(e) {
  550.         alert("Failed to set " + prefname + " to " + prefvalue);
  551.     }
  552. }
  553.  
  554. function getIntPref(prefname, prefdef) {
  555.     var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
  556.     try{
  557.         return pref.getIntPref(prefname);
  558.     } catch(e) {
  559.         pref.setIntPref(prefname, prefdef);
  560.         return pref.getIntPref(prefname);
  561.     }
  562. }
  563.  
  564. function setIntPref(prefname, prefvalue) {
  565.     var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
  566.     try{
  567.         pref.setIntPref(prefname, prefvalue);
  568.     } catch(e) {
  569.         alert("Failed to set " + prefname + " to " + prefvalue);
  570.     }
  571. }
  572.  
  573. function getCharPref(prefname, prefdef) {
  574.     var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
  575.     try{
  576.         return pref.getCharPref(prefname);
  577.     } catch(e) {
  578.         pref.setCharPref(prefname, prefdef);
  579.         return pref.getCharPref(prefname);
  580.     }
  581. }
  582.  
  583. function setCharPref(prefname, prefvalue) {
  584.     var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
  585.     try{
  586.         pref.setCharPref(prefname, prefvalue);
  587.         return true;
  588.     } catch(e) {
  589.         return false;
  590.     }
  591. }
  592.  
  593. function createRegkey(root, path, keyname) {
  594.     try {
  595.         var fullpath = path + "\\" + keyname;
  596.         var regKey = Components.classes["@mozilla.org/windows-registry-key;1"].createInstance(Components.interfaces.nsIWindowsRegKey);
  597.         regKey.create(root, fullpath, Components.interfaces.nsIWindowsRegKey.ACCESS_WRITE);
  598.         return true;
  599.       } catch(regErr) {
  600.           return false;
  601.       }
  602. }
  603.  
  604. function getRegkey(root, path, keyname) {
  605.     try {
  606.         var regKey = Components.classes["@mozilla.org/windows-registry-key;1"].createInstance(Components.interfaces.nsIWindowsRegKey);
  607.         regKey.open(root, path, Components.interfaces.nsIWindowsRegKey.ACCESS_READ);
  608.         return regKey.readStringValue(keyname);
  609.       } catch(regErr) {
  610.           return "";
  611.       }
  612. }
  613.  
  614. function setRegkey(root, path, keyname, value) {
  615.     try {
  616.         var regKey = Components.classes["@mozilla.org/windows-registry-key;1"].createInstance(Components.interfaces.nsIWindowsRegKey);
  617.         regKey.open(root, path, Components.interfaces.nsIWindowsRegKey.ACCESS_WRITE);
  618.         return regKey.writeStringValue(keyname, value);
  619.       } catch(regErr) {
  620.           return "";
  621.       }
  622. }
  623.  
  624. function getCharMachineRegkey(path, keyname) {
  625.     try {
  626.         var fullpath = "SOFTWARE\\SiteAdvisor\\" + path;
  627.         return getRegkey(Components.interfaces.nsIWindowsRegKey.ROOT_KEY_LOCAL_MACHINE, fullpath, keyname);
  628.       } catch(regErr) {
  629.           return "";
  630.       }
  631. }
  632.  
  633. function createCharUserRegkey(path, keyname) {
  634.     try {
  635.         var fullpath = "SOFTWARE" + path;
  636.         return createRegkey(Components.interfaces.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER, fullpath, keyname);
  637.       } catch(regErr) {
  638.           return false;
  639.       }
  640. }
  641.  
  642. function getCharUserRegkey(path, keyname) {
  643.     try {
  644.         var fullpath = "SOFTWARE\\SiteAdvisor\\" + path;
  645.         return getRegkey(Components.interfaces.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER, fullpath, keyname);
  646.       } catch(regErr) {
  647.           return "";
  648.       }
  649. }
  650.  
  651. function setCharUserRegkey(path, keyname, value) {
  652.     try {
  653.         var fullpath = "SOFTWARE\\SiteAdvisor\\" + path;
  654.         return setRegkey(Components.interfaces.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER, fullpath, keyname, value);
  655.       } catch(regErr) {
  656.           return false;
  657.       }
  658. }
  659.  
  660. function getBoolMachineRegkey(path, keyname) {
  661.       var value = getCharMachineRegkey(path, keyname);
  662.  
  663.       if (value == "true")
  664.             return true;
  665.  
  666.     return false;
  667. }
  668.  
  669. function getSaXPCom() {
  670.     if (!compareFirefoxVersion("1.5")) {
  671.         try {
  672.             netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
  673.             const cid = "@siteadvisor.com/SiteAdvisor/FFHook;1";
  674.             obj = Components.classes[cid].createInstance();
  675.             return obj.QueryInterface(Components.interfaces.IFFHook);
  676.         } catch (err) {
  677.          }
  678.      }
  679. }
  680.  
  681. // LKV = last known version
  682. function getLKV() {
  683.     var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
  684.     try{
  685.         return parseFloat(pref.getCharPref("extensions.safe.lastKnownVersion"));
  686.     } catch(e) {
  687.         pref.setCharPref("extensions.safe.lastKnownVersion","0");
  688.         return parseFloat(pref.getCharPref("extensions.safe.lastKnownVersion"));
  689.     }
  690. }
  691.  
  692. function setLKV(lkv) {
  693.     setCharPref("extensions.safe.lastKnownVersion",lkv);
  694. }
  695.  
  696.  
  697. function getBuild() {
  698.     return getIntPref("extensions.safe.build", 0);
  699. }
  700.  
  701. function setBuild(build) {
  702.     setIntPref("extensions.safe.build",build);
  703. }
  704.  
  705. function getDss() {
  706.     return getCharPref("extensions.safe.dss","http://dss1.siteadvisor.com/DSS/");
  707. }
  708.  
  709. function setDss(dss) {
  710.     setCharPref("extensions.safe.dss",dss);
  711. }
  712.  
  713. function getUninstalled() {
  714.     return getBoolPref("extensions.safe.uninstalled");
  715. }
  716.  
  717. function getButtonEnabled() {
  718.     return getBoolPref("extensions.safe.enablebutton", true);
  719. }
  720.  
  721. function setButtonEnabled(enabled) {
  722.     return setBoolPref("extensions.safe.enablebutton", enabled);
  723. }
  724.  
  725. function getProtectedSurf() {
  726.     try
  727.     {
  728.         var interface = getSaXPCom();
  729.         return interface.GetProtectedMode();
  730.     }
  731.     catch(e)
  732.     {
  733.     }
  734. }
  735.  
  736. function getPsurfEnabled() {
  737.     return (getProtectedSurf() == "Restricted");
  738. }
  739.  
  740. function getPsurfInitialized() {
  741.     var protectedSurf = getProtectedSurf();
  742.     return ((protectedSurf != "Uninitialized"));
  743. }
  744.  
  745. function getPremium() {
  746.      try {
  747.          var interface = getSaXPCom();
  748.         if(mode && mode==BASIC)
  749.             return false;
  750.          return interface.IsPremium();
  751.      } catch(err) {
  752.          return false;
  753.      }
  754. }
  755.  
  756. function getSSL() {
  757.     try
  758.     {
  759.         var interface = getSaXPCom();
  760.         return interface.GetUseSSL();
  761.     }
  762.     catch(e)
  763.     {
  764.         return getBoolPref("extensions.safe.doSSL", false);
  765.     }
  766. }
  767.  
  768. function setSSL(enabled) {
  769.     try
  770.     {
  771.         var interface = getSaXPCom();
  772.         return interface.SetUseSSL(enabled);
  773.     }
  774.     catch(e)
  775.     {
  776.         return setBoolPref("extensions.safe.doSSL", enabled);
  777.     }
  778. }
  779.  
  780. function getHighlight() {
  781.     try
  782.     {
  783.         var interface = getSaXPCom();
  784.         return interface.GetSafeSearchHighlight();
  785.     }
  786.     catch(e)
  787.     {
  788.         return getBoolPref("extensions.safe.highlight", false);
  789.     }
  790. }
  791.  
  792. function setHighlight(enabled) {
  793.     try
  794.     {
  795.         var interface = getSaXPCom();
  796.         interface.SetSafeSearchHighlight(enabled);
  797.     }
  798.     catch(e)
  799.     {
  800.         return setBoolPref("extensions.safe.highlight", enabled);
  801.     }
  802. }
  803.  
  804. function getSafeOn() {
  805.     try
  806.     {
  807.         var interface = getSaXPCom();
  808.         return interface.GetSafesearchIcons();
  809.     }
  810.     catch(e)
  811.     {
  812.         return getBoolPref("extensions.safe.on", true);
  813.     }
  814. }
  815.  
  816. function setSafeOn(enabled) {
  817.     try
  818.     {
  819.         var interface = getSaXPCom();
  820.         return interface.SetSafesearchIcons(enabled);
  821.     }
  822.     catch(e)
  823.     {
  824.         return setBoolPref("extensions.safe.on", enabled);
  825.     }
  826. }
  827.  
  828. function getWhitelist() {
  829.     try
  830.     {
  831.         var interface = getSaXPCom();
  832.         var whitelist = interface.GetWhitelistSites()
  833.         return whitelist;
  834.     }
  835.     catch (err)
  836.     {
  837.         return  getCharPref("extensions.safe.whitelist", "");
  838.     }
  839. }
  840.  
  841. function getPassword() {
  842.     return getCharMachineRegkey("Premium", "PasswordHash");
  843. }
  844.  
  845. function getHint() {
  846.     return getCharMachineRegkey("Premium", "PasswordHint");
  847. }
  848.  
  849. function getSuite() {
  850.     return getCharMachineRegkey("", "HasSuite");
  851. }
  852.  
  853. function getUID() {
  854.     return getCharUserRegkey("", "UID");
  855. }
  856.  
  857. function getFullVersion() {
  858.     var client_version  = "FF_unknown";
  859.     try {
  860.         client_version = "FF_" + getVersion();
  861.         client_version += "_" + getBuild();
  862.     } catch (versionerr) {}
  863.     return client_version;
  864. }
  865.  
  866. function checkSSL(dssurl) {
  867.    if (dssurl.match(/^https:/)) return dssurl;
  868.    if (doSSL)
  869.       return dssurl.replace(/^http:/,"https:");
  870.    else return dssurl;
  871. }
  872.  
  873. function sendUpgradePing() {
  874.     try{
  875.         var request = new XMLHttpRequest();
  876.             request.open("GET", checkSSL(getDss()) + "Ping?Version=2&Type=upgrade&client_type=SAFE&client_ver=" +getFullVersion()+"&locale="+getLocale()+"&aff_id="+getAffid()+"&UID="+getGuid(), true);
  877.             request.send(null);
  878.     } catch(comerr) {}
  879. }
  880.  
  881. // see if its time to send a ping and send if necessary
  882. function pingDSS() {
  883.     // get last daily and monthly from prefs (in string millisecond format)
  884.     var lastDaily = getLastDailyPing();
  885.     var lastMonthly = getLastMonthlyPing();
  886.  
  887.     // convert string dates into Date objects
  888.     var lastDailyDate = new Date(lastDaily);
  889.     var lastMonthlyDate = new Date(lastMonthly);
  890.  
  891.     // get the "next month" and "next day" in milliseconds
  892.     var nextMonth = lastMonthlyDate.setUTCMonth(lastMonthlyDate.getUTCMonth()+1);
  893.     var nextDay = lastDailyDate.setUTCDate(lastDailyDate.getUTCDate()+1);
  894.  
  895.     // get "right now" in milliseconds
  896.     var rightNowDate = new Date();
  897.     var rightNow = rightNowDate.getTime();
  898.  
  899.     // if a month has passed, send a monthly
  900.     if (nextMonth < rightNow) {
  901.  
  902.         // try to send monthly
  903.                try {
  904.                   request = new XMLHttpRequest();
  905.                   request.open("GET", checkSSL(getDss()) + "Ping?Version=2&Type=monthly&client_type=SAFE&client_ver=" + getFullVersion()+"&locale="+getLocale()+"&UID="+getGuid(), false);
  906.                   request.overrideMimeType('text/xml');
  907.                   request.setRequestHeader("Accept-Encoding", "");
  908.                   request.send(null);
  909.                   var stat;
  910.           try {stat = request.status;}
  911.                   catch(staterr) {stat = 500;}
  912.                   if (stat != 200 || request.responseXML.documentElement.nodeName == "parsererror") return;
  913.                   if (request.responseXML.getElementsByTagName("PingResponse").length == 0) return;
  914.                 } catch(pingreqerr) {
  915.                   return;
  916.                 }
  917.  
  918.                 // update last daily to NOW
  919.         rightNowDate.setUTCHours(0);
  920.         rightNowDate.setUTCMinutes(0);
  921.         rightNowDate.setUTCSeconds(0);
  922.         rightNow = rightNowDate.getTime();
  923.         setLastDailyPing(rightNow);
  924.  
  925.         // update last monthly to 1st of month
  926.         rightNowDate.setUTCDate(1);
  927.         rightNow = rightNowDate.getTime();
  928.         setLastMonthlyPing(rightNow);
  929.  
  930.     // otherwise, if a day has passed, send a daily
  931.     } else if (nextDay < rightNow) {
  932.  
  933.         // try to send daily
  934.                 try {
  935.                   request = new XMLHttpRequest();
  936.                   request.open("GET", checkSSL(getDss()) + "Ping?Version=2&Type=daily&client_type=SAFE&client_ver=" + getFullVersion()+"&locale="+getLocale()+"&aff_id="+getAffid()+"&UID="+getGuid(), false);
  937.                   request.overrideMimeType('text/xml');
  938.                   request.setRequestHeader("Accept-Encoding", "");
  939.                   request.send(null);
  940.                   var stat;
  941.           try {stat = request.status;}
  942.                   catch(staterr) {stat = 500;}
  943.                   if (stat != 200 || request.responseXML.documentElement.nodeName == "parsererror") return;
  944.                   if (request.responseXML.getElementsByTagName("PingResponse").length == 0) return;
  945.                 } catch(pingreqerr) {
  946.                   return;
  947.                 }
  948.  
  949.         // update last daily to NOW
  950.         rightNowDate.setUTCHours(0);
  951.         rightNowDate.setUTCMinutes(0);
  952.         rightNowDate.setUTCSeconds(0);
  953.         rightNow = rightNowDate.getTime();
  954.         setLastDailyPing(rightNow);
  955.     }
  956. }
  957.  
  958. function getLocale() {
  959.   try {
  960.     var ffLocale = navigator.language;
  961.     var langPart = ffLocale.split("-")[0];
  962.     var langMatch;
  963.     for (var l = 0; l < McLocales.length; l++) {
  964.       if (McLocales[l] == ffLocale) return ffLocale;
  965.       if (!langMatch && McLocales[l].split("-")[0] == langPart) langMatch = McLocales[l];
  966.     }
  967.     return langMatch ? langMatch : "en-US";
  968.   } catch(e) {
  969.     return "en-US";
  970.   }
  971. }
  972.  
  973. function getLastDailyPing() {
  974.     var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
  975.     try{
  976.         return parseFloat(pref.getCharPref("extensions.safe.lastDailyPing"));
  977.     } catch(e) {
  978.         pref.setCharPref("extensions.safe.lastDailyPing","0");
  979.         return parseFloat(pref.getCharPref("extensions.safe.lastDailyPing"));
  980.     }
  981. }
  982.  
  983. function setLastDailyPing(t) {
  984.     setCharPref("extensions.safe.lastDailyPing",t.toString());
  985. }
  986.  
  987. function getLastMonthlyPing() {
  988.     var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
  989.     try{
  990.         return parseFloat(pref.getCharPref("extensions.safe.lastMonthlyPing"));
  991.     } catch(e) {
  992.         pref.setCharPref("extensions.safe.lastMonthlyPing","0");
  993.         return parseFloat(pref.getCharPref("extensions.safe.lastMonthlyPing"));
  994.     }
  995. }
  996.  
  997. function setLastMonthlyPing(t) {
  998.     setCharPref("extensions.safe.lastMonthlyPing",t.toString());
  999. }
  1000.  
  1001. function check_auto_update() {
  1002.     if (!( getBoolPref("extensions.safe.enablebutton", true) ||
  1003.         getBoolPref("extensions.safe.on", true) ||
  1004.         getBoolPref("extensions.safe.highlight", false)))
  1005.         return;
  1006.  
  1007.     var areq = new XMLHttpRequest();
  1008.  
  1009.     areq.open('GET',"https://sadownload.mcafee.com/products/sa/firefox/update.rdf", true);
  1010.  
  1011.     areq.overrideMimeType('text/plain');
  1012.     areq.onreadystatechange = function () {
  1013.         try{
  1014.         if (areq.readyState == 4) {
  1015.             var stat;
  1016.             try {
  1017.                 stat = areq.status;
  1018.             } catch (staterr) {
  1019.                 stat = 500;
  1020.             }
  1021.             if (stat == 200){
  1022.                 resp = areq.responseText;
  1023.  
  1024.                 start = resp.indexOf("<version>");
  1025.                 end = resp.indexOf("</version>");
  1026.                 newest_version = parseFloat(resp.substring(start+9,end));
  1027.  
  1028.                 var VERSION = parseFloat(getVersion());
  1029.                 // check if the server has a newer version
  1030.                 if (newest_version > VERSION) {
  1031.                     var install = confirm(strb("safe.updateRequiredResponse"));
  1032.                     if (install) {
  1033.                         // Extension force-Auto-update code
  1034.                         var nsIUpdateItem = Components.interfaces.nsIUpdateItem;
  1035.                         var gExtensionManager = Components.classes["@mozilla.org/extensions/manager;1"].getService(Components.interfaces.nsIExtensionManager);
  1036.                         var itemType=nsIUpdateItem.TYPE_EXTENSION;
  1037.                         var items;
  1038.                         try{
  1039.                             items = gExtensionManager.getItemList('{1650a312-02bc-40ee-977e-83f158701739}', itemType, { });
  1040.                             var updates = Components.classes["@mozilla.org/updates/update-service;1"].getService(Components.interfaces.nsIUpdateService);
  1041.                             updates.checkForUpdates(items, items.length, itemType, Components.interfaces.nsIUpdateService.SOURCE_EVENT_USER, window);
  1042.  
  1043.                         } catch(ve) {
  1044.                             // Firefox 1.5 makes this tons of fun...
  1045.  
  1046.                             item = gExtensionManager.getItemForID('{1650a312-02bc-40ee-977e-83f158701739}');
  1047.                             items = new Array();
  1048.                             items[0] = item;
  1049.                             updateListener = new Object();
  1050.                             updateListener.onUpdateStarted = function() {};
  1051.                             updateListener.onUpdateEnded = function() {};
  1052.                             updateListener.onAddonUpdateStarted = function(addon) {};
  1053.                             updateListener.onAddonUpdateEnded = function(addon,status) {
  1054.                                 if (status == 1) {
  1055.                                     var xpimgr = Components.classes["@mozilla.org/xpinstall/install-manager;1"].createInstance(Components.interfaces.nsIXPInstallManager);
  1056.                                     urls = new Array();
  1057.                                     urls[0] = addon.xpiURL;
  1058.                                     progress = new Object();
  1059.                                     progress.onStateChange = function(idx,st,val) {
  1060.                                         if (st == Components.interfaces.nsIXPIProgressDialog.INSTALL_DONE) {
  1061.                                            restart = confirm(strb("safe.closeFFRequest"));
  1062.                                            if (restart) {
  1063.                                             var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator);
  1064.                                             var enumerator = wm.getEnumerator("");
  1065.                                             while(enumerator.hasMoreElements()) {
  1066.                                                 var win = enumerator.getNext();
  1067.                                                 win.close();
  1068.                                             }
  1069.                                            }
  1070.                                         }
  1071.                                     }
  1072.                                     progress.onProgress = function(idx,val,mval) {}
  1073.                                     xpimgr.initManagerFromChrome(urls,1,progress);
  1074.                                 }
  1075.                             };
  1076.                             gExtensionManager.update(items,1,false,updateListener);
  1077.                         }
  1078.                     }
  1079.                     else
  1080.                     {
  1081.                         //alert(strb("safe.turnOffSafe"));
  1082.                     }
  1083.                 }
  1084.             }
  1085.         }
  1086.         } catch(e) {}
  1087.     };
  1088.     areq.send(null);
  1089. }
  1090.  
  1091. function getVersion() {
  1092.     try{
  1093.  
  1094.     var RDFServ = Components.classes["@mozilla.org/rdf/rdf-service;1"].getService(Components.interfaces.nsIRDFService);
  1095.     var versionRDF = RDFServ.GetResource("http://www.mozilla.org/2004/em-rdf#version");
  1096.     var extension_data_source= Components.classes["@mozilla.org/extensions/manager;1"].getService(Components.interfaces.nsIExtensionManager).datasource;
  1097.  
  1098.  
  1099.     var nameArc = RDFServ.GetResource("http://www.mozilla.org/2004/em-rdf#name");
  1100.     var Container = Components.classes["@mozilla.org/rdf/container;1"].getService(Components.interfaces.nsIRDFContainer);
  1101.     try {
  1102.         var root = RDFServ.GetResource("urn:mozilla:item:root");
  1103.         Container.Init(extension_data_source,root);
  1104.     } catch(e) {
  1105.         var root = RDFServ.GetResource("urn:mozilla:extension:root");
  1106.         Container.Init(extension_data_source,root);
  1107.  
  1108.     }
  1109.     var elements=Container.GetElements();
  1110.     while (elements.hasMoreElements()) {
  1111.         var element = elements.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
  1112.             var target = extension_data_source.GetTarget(element, nameArc ,true);
  1113.         if (target) {
  1114.             name = target.QueryInterface(Components.interfaces.nsIRDFLiteral).Value;
  1115.             if (name == "McAfee SiteAdvisor")
  1116.                 return extension_data_source.GetTarget(element, versionRDF, true).QueryInterface(Components.interfaces.nsIRDFLiteral).Value;
  1117.         }
  1118.     }
  1119.     return strb("safe.unknownVersion");
  1120.     } catch (allerr) {
  1121.     return strb("safe.unknownVersion");
  1122.     }
  1123. }
  1124.  
  1125.  
  1126. function stripargs(loc) {
  1127.     i = loc.indexOf("?")
  1128.     if (i != -1)
  1129.         loc = loc.substring(0,i);
  1130.     i = loc.indexOf("&")
  1131.     if (i != -1)
  1132.         loc = loc.substring(0,i);
  1133.     i = loc.indexOf(";")
  1134.     if (i != -1)
  1135.         loc = loc.substring(0,i);
  1136.     i = loc.indexOf(",")
  1137.     if (i != -1)
  1138.         loc = loc.substring(0,i);
  1139.     i = loc.indexOf("'")
  1140.     if (i != -1)
  1141.         loc = loc.substring(0,i);
  1142.     i = loc.indexOf(" ")
  1143.     if (i != -1)
  1144.         loc = loc.substring(0,i);
  1145.  
  1146.     locsplit = loc.split(/\/+/);
  1147.  
  1148.     /*
  1149.     if (loc.match(/^https:/) || loc.match(/^http:/) || loc.match(/^ftp:/)) {
  1150.         if (locsplit.length > 4)
  1151.             loc = locsplit[0] + "//" + locsplit[1] + "/" + locsplit[2] + "/" + locsplit[3] + "/";
  1152.     } else {
  1153.         if (locsplit.length > 3)
  1154.             loc = locsplit[0] + "/" + locsplit[1] + "/" + locsplit[2] + "/";
  1155.     }
  1156.     */
  1157.     
  1158.     return loc;
  1159. }
  1160.  
  1161. function addToCache(uds, verdict, color, popularity, regxp, pBl) {
  1162.     newregxp = "";
  1163.     for (var c = 0; c < regxp.length; c++) {
  1164.         if (regxp[c] == "}")
  1165.             newregxp += ")";
  1166.         else if (regxp[c] == "{")
  1167.             newregxp += "(?:";
  1168.         else if (regxp[c] == "/")
  1169.             newregxp += "\\/";
  1170.         else newregxp += regxp[c];
  1171.     }
  1172.  
  1173.     newEntry = new Object();
  1174.     newEntry["ds"] = uds;
  1175.     newEntry["vd"] = verdict;
  1176.     newEntry["ts"] = (new Date()).getTime();
  1177.     newEntry["its"] = (new Date()).getTime();
  1178.     newEntry["co"] = color;
  1179.     newEntry["pop"] = popularity;
  1180.     newEntry["pbl"] = pBl;
  1181.     
  1182.     regexmap[regexmap.length] = newregxp;
  1183.  
  1184.     if (udscache.length >= cachesize) {
  1185.         min = 0
  1186.         for (var i = 1; i < udscache.length; i++) {
  1187.             if (udscache[i]["its"] + cachettl < (new Date()).getTime()) {
  1188.                 min = i;
  1189.                 break;
  1190.             }
  1191.             if (udscache[i]["ts"] < udscache[min]["ts"])
  1192.                 min = i
  1193.         }
  1194.  
  1195.         udscache[min] = newEntry;
  1196.  
  1197.     } else {
  1198.         udscache[udscache.length] = newEntry;
  1199.     }
  1200. }
  1201.  
  1202. function getFromCache(mURL) {
  1203.     var dsfrommap = getDsFromMap(mURL);
  1204.     if (!dsfrommap)
  1205.         return false;
  1206.     var entryfromcache = getEntryFromCache(dsfrommap);
  1207.     if (!entryfromcache)
  1208.         return false;
  1209.     return entryfromcache;
  1210. }
  1211.  
  1212. function getDsFromMap(mURL) {
  1213.     for (var i = 0; i < regexmap.length; i++) {
  1214.         regxp = regexmap[i];
  1215.         regxps = regxp.split(/\s/);
  1216.  
  1217.         for (var r = 0; r < regxps.length; r++) {
  1218.             try{
  1219.               eval("var rem = mURL.match(/" + regxps[r] + "/);");
  1220.               if (rem) {
  1221.                 return rem[rem.length-1];
  1222.               }
  1223.             } catch (rexe) {}
  1224.         }
  1225.     }
  1226.  
  1227.     return false;
  1228. }
  1229.  
  1230. function getEntryFromCache(ds) {
  1231.     for (var i = 0; i < udscache.length; i++) {
  1232.         if (udscache[i]["ds"] == ds) {
  1233.  
  1234.             if (udscache[i]["its"] + cachettl < (new Date()).getTime())
  1235.                 continue;
  1236.             else
  1237.                 return udscache[i];
  1238.         }
  1239.     }
  1240.     return false;
  1241. }
  1242.  
  1243. function updateCache(cacheEntry) {
  1244.     cacheEntry["ts"] = (new Date()).getTime();
  1245. }
  1246.  
  1247. function bad_host(h) {
  1248.     if (h == ""              ||
  1249.         h.match(/[^a-z0-9\.\-]/)    ||
  1250.             h == "localhost"     ||
  1251.             h == "127.0.0.1"     ||
  1252.             (h.indexOf(".") == -1 && !h.match(/^\d+$/)) ||
  1253.             h.indexOf(".") == 0  ||
  1254.         h.match(/^10\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) ||
  1255.         h.match(/^172\.(1[6-9]|2[0-9]|3[0-1])\.\d{1,3}\.\d{1,3}$/) ||
  1256.         h.match(/^192\.168\.\d{1,3}\.\d{1,3}$/) ||
  1257.         h.match(/\.localdomain$/) ||
  1258.             h.match(/\.local$/))  {
  1259.         return true;
  1260.         }
  1261.     return false;
  1262. }
  1263.  
  1264. function bad_protocol(p) {
  1265.     if (p.indexOf("http:") == 0      ||
  1266.             p.indexOf("https:") == 0     ||
  1267.             p.indexOf("ftp:") == 0)
  1268.         return false;
  1269.  
  1270.     return true;
  1271. }
  1272.  
  1273. var ffhook;
  1274.  
  1275. var listener = {
  1276.     QueryInterface : function(aIID)
  1277.     {
  1278.         if (aIID.equals(Components.interfaces.nsIPhishListener) ||
  1279.             aIID.equals(Components.interfaces.nsISupports) )
  1280.         {
  1281.             return this;
  1282.         }
  1283.  
  1284.         throw Components.results.NS_NOINTERFACE;
  1285.         Components.returnCode = Components.results.NS_ERROR_NO_INTERFACE;
  1286.         return null;
  1287.     },
  1288.  
  1289.     onLookupComplete: function(cookie, val, url)
  1290.     {
  1291.         if (val != 0) {
  1292.             var url = "http://www.siteadvisor.com/phishing.html?domain=" + sloc + "&suite=false&premium=" + premium + "&client_type=FF&client_ver=" + getFullVersion();
  1293.             window.content.location.replace(url);
  1294.         }
  1295.     },
  1296.  
  1297.     onLookupFailed: function(cookie, val, url)
  1298.     {
  1299.         try {
  1300.             //alert("onLookupFailed " + cookie + " " + val);
  1301.         } catch(err) {
  1302.             //alert(err);
  1303.         }
  1304.     }
  1305. }
  1306.  
  1307. function load_handler(e) {
  1308.     changebutton();
  1309. }
  1310.  
  1311. function is_whitelisted(wdomain,domain) {
  1312.     var ldomain = domain.toLowerCase();
  1313.     var wldomain = wdomain.toLowerCase().replace(/\./g,"\\.");
  1314.     wldomain = wldomain.replace(/\//g,"\/")
  1315.     var exp = new RegExp("^([^/]*\\.)?"+wldomain+"(/.*)?$");
  1316.     if(ldomain.match(exp))
  1317.     {
  1318.         return true;
  1319.     }
  1320.     return false;
  1321. }
  1322.  
  1323. function checkForRedirect(classification, popularity) {
  1324.     if (classification != "certified") {
  1325.         whitelistedDomains = getWhitelist();
  1326.         var whitelistedDomainsArray = whitelistedDomains.split(";");
  1327.         var count = whitelistedDomainsArray.length;
  1328.  
  1329.         while (count--) {
  1330.               var item = whitelistedDomainsArray[count];
  1331.  
  1332.               if (item == domain_specifier)
  1333.                 return;
  1334.             if(is_whitelisted(domain_specifier,item))
  1335.                 return;
  1336.           }
  1337.  
  1338.         psurf = getPsurfEnabled();
  1339.  
  1340.         if (premium && psurf && ((classification == "warn") || (classification == "info"))) {
  1341.             var url = "http://www.siteadvisor.com/restricted.html?domain=" + domain_specifier + "&" + buildArgString();
  1342.             window.content.location.replace(url);
  1343.         }
  1344.     }
  1345. }
  1346.  
  1347. function changebutton() {
  1348.     try{
  1349.         if (!buttonon) {
  1350.             document.getElementById("SAFE-TB-Combined").setAttribute("image","chrome://safe/content/safe.gif");
  1351.             return;
  1352.         }
  1353.  
  1354.         domain_specifier = "";
  1355.         loc = window._content.location.href;
  1356.  
  1357.         document.getElementById("SAFE-TB-Combined").setAttribute("image","chrome://safe/content/safe.gif");
  1358.         var h = "";
  1359.         var p = "";
  1360.         var pn = "";
  1361.         try{
  1362.             h = window._content.location.host.toLowerCase();
  1363.             portsplit = h.split(":");
  1364.             if (portsplit.length == 2)
  1365.                 h = portsplit[0];
  1366.             p = window._content.location.protocol.toLowerCase();
  1367.             pn = window._content.location.pathname;
  1368.  
  1369.         } catch(he) {return;}
  1370.  
  1371.         if (bad_host(h))
  1372.             return;
  1373.         if (bad_protocol(p))
  1374.             return;
  1375.  
  1376.         sloc = stripargs(h + pn);
  1377.         cacheEntry = getFromCache(sloc);
  1378.         globalSloc=sloc;
  1379.         if (cacheEntry) {
  1380.             domain_specifier = cacheEntry["ds"];
  1381.             try
  1382.             {
  1383.                 var pBl = cacheEntry["pbl"];
  1384.                 var isPhish = checkForPhishing(pBl,loc,domain_specifier);
  1385.                 if(isPhish) return;
  1386.             }
  1387.             catch(e)
  1388.             {
  1389.             }
  1390.             
  1391.             var classification = cacheEntry["vd"].toLowerCase();
  1392.             var popularity = cacheEntry["pop"];
  1393.  
  1394.             checkForRedirect(classification, popularity);
  1395.  
  1396.             if (classification == "unknown")
  1397.                 document.getElementById("SAFE-TB-Combined").setAttribute("image","chrome://safe/content/safe.gif");
  1398.             else
  1399.                 document.getElementById("SAFE-TB-Combined").setAttribute("image","chrome://safe/content/safe-" + cacheEntry["co"].toLowerCase() + ".gif");
  1400.  
  1401.             updateCache(cacheEntry);
  1402.             return;
  1403.         }
  1404.  
  1405.         sloc=extractHostName(sloc);
  1406.         makeDssQueryPriv("Query?Entitlement=FOO&Type=domain&version=2&name="+escape(sloc)+"&client_ver="+getFullVersion()+"&locale="+getLocale()+"&aff_id="+getAffid(),loc);
  1407.     } catch(e) {}
  1408. }
  1409.  
  1410. function changebutton_URI(URI)
  1411. {
  1412.     try{
  1413.         docloc = URI.asciiSpec;
  1414.         if (docloc == loc) 
  1415.         {
  1416.             return;
  1417.         }
  1418. //        alert("loc: " + loc);
  1419. //        alert("docloc: " + docloc);
  1420.  
  1421.  
  1422.         if (!buttonon) {
  1423.             document.getElementById("SAFE-TB-Combined").setAttribute("image","chrome://safe/content/safe.gif");
  1424.             return;
  1425.         }
  1426.  
  1427.         domain_specifier = "";
  1428.         loc = URI.asciiSpec;
  1429.  
  1430.         document.getElementById("SAFE-TB-Combined").setAttribute("image","chrome://safe/content/safe.gif");
  1431.         var h = "";
  1432.         var p = "";
  1433.         var pn = "";
  1434.         try{
  1435.             h = URI.host.toLowerCase();
  1436.             portsplit = h.split(":");
  1437.             if (portsplit.length == 2)
  1438.                 h = portsplit[0];
  1439.             p = URI.scheme.toLowerCase();
  1440.             pn = URI.path;
  1441.  
  1442.         } catch(he) {return;}
  1443.  
  1444.         if (bad_host(h))
  1445.         {
  1446.             return;
  1447.         }
  1448.  
  1449.         // hack...nsIURL returns scheme without ":"                
  1450.         if (bad_protocol(p+":"))
  1451.         {
  1452.             return;
  1453.         }
  1454.  
  1455.         sloc = stripargs(h + pn);
  1456.         cacheEntry = getFromCache(sloc);
  1457.         globalSloc=sloc;
  1458.         if (cacheEntry) {
  1459.             domain_specifier = cacheEntry["ds"];
  1460.             try
  1461.             {
  1462.                 var pBl = cacheEntry["pbl"];
  1463.                 var isPhish = checkForPhishing(pBl,loc, domain_specifier);
  1464.                 if(isPhish) return;
  1465.             }
  1466.             catch(e)
  1467.             {
  1468.             }
  1469.             
  1470.             var classification = cacheEntry["vd"].toLowerCase();
  1471.             var popularity = cacheEntry["pop"];
  1472.  
  1473.             checkForRedirect(classification, popularity);
  1474.  
  1475.             if (classification == "unknown")
  1476.                 document.getElementById("SAFE-TB-Combined").setAttribute("image","chrome://safe/content/safe.gif");
  1477.             else
  1478.                 document.getElementById("SAFE-TB-Combined").setAttribute("image","chrome://safe/content/safe-" + cacheEntry["co"].toLowerCase() + ".gif");
  1479.  
  1480.             updateCache(cacheEntry);
  1481.             return;
  1482.         }
  1483.  
  1484.         sloc=extractHostName(sloc);
  1485.         makeDssQueryPriv("Query?Entitlement=FOO&Type=domain&version=2&name="+escape(sloc)+"&client_ver="+getFullVersion()+"&locale="+getLocale()+"&aff_id="+getAffid(),loc);
  1486.     } catch(e) {}
  1487. }
  1488.  
  1489. var globalSloc;
  1490.  
  1491. function makeDssQueryPriv(dssquery,loc) {
  1492.     var dssurl = getDss();
  1493.     httpGetRequestPriv(dssurl, dssquery, true, true,null,false,loc);
  1494. }
  1495.  
  1496. function httpGetRequestPriv(dssurl,dssquery,retry,timeout,oldreq,forceSSL,loc) {
  1497.     if (oldreq) {
  1498.         if (oldreq.timeoutId) clearTimeout(oldreq.timeoutId);
  1499.         oldreq.onreadystatechange = null;
  1500.         oldreq.abort();
  1501.     }
  1502.     var greq = new XMLHttpRequest();
  1503.     if (timeout) {
  1504.         greq.timeoutId = setTimeout(retryDssQueryPriv,10000,dssurl,dssquery,greq,forceSSL,loc);
  1505.         greq.onprogress = function () {
  1506.             clearTimeout(greq.timeoutId);
  1507.             greq.timeoutId = setTimeout(retryDssQueryPriv,10000,dssurl,dssquery,greq,forceSSL,loc);
  1508.         }
  1509.     }
  1510.  
  1511.     greq.open('GET',(forceSSL? useSSL(dssurl) : checkSSL(dssurl)) + dssquery, true);
  1512.     greq.overrideMimeType('text/xml');
  1513.     greq.setRequestHeader("Accept-Encoding", "");
  1514.     greq.onreadystatechange = function () {
  1515.         if (greq.readyState == 4) {
  1516.             var stat;
  1517.             try {stat = greq.status;}
  1518.             catch(staterr) {stat = 500;}
  1519.             if (greq.timeoutId) clearTimeout(greq.timeoutId);
  1520.             if (stat == 200 && greq.responseXML.documentElement.nodeName != "parsererror") {
  1521.                 DSSResponseHandlerPriv(greq.responseXML,dssquery,loc);
  1522.             } else if (retry) {
  1523.                 retryDssQueryPriv(dssurl,dssquery,greq,forceSSL,loc);
  1524.             } else {
  1525.                 DSSFailureHandler(dssquery);
  1526.             }
  1527.         }
  1528.     };
  1529.     greq.send(null);
  1530. }
  1531.  
  1532. function DSSResponseHandlerPriv(xml,dssquery,loc) {
  1533.     var responseHandlers = {'PingResponse': versionHandler,
  1534.                     'DomainQueryResponse': SingleQueryDSSHandlerPriv};
  1535.         var handlerFound = false;
  1536.     for (var key in responseHandlers)
  1537.         if (xml.getElementsByTagName(key).length == 1) {
  1538.             responseHandlers[key](xml,loc);
  1539.                         handlerFound = true;
  1540.         }
  1541.         if (!handlerFound) {
  1542.           checkForEmergency(xml);
  1543.           DSSFailureHandler(dssquery);
  1544.         }
  1545. }
  1546.  
  1547. var orK  = "78600D4531B00B42"
  1548.  
  1549. function XOR(i,j)
  1550. {
  1551.     x = i^j;
  1552.     return x;
  1553. }
  1554.  
  1555. function hexToDec(h) {return parseInt(h,16);}
  1556.  
  1557. function dec(encM)
  1558. {
  1559.     try
  1560.     {
  1561.         var cusK = expK(encM);
  1562.         var entity = encM.length/2;
  1563.         var decM = "";
  1564.         for(var i=0;i<entity;i++)
  1565.         {
  1566.             var op1 = hexToDec(cusK.slice((2*i),(2*i + 2)));
  1567.             var op2 = hexToDec(encM.slice((2*i),(2*i + 2)));
  1568.             var ch = XOR(op1,op2);
  1569.             decM+=String.fromCharCode(ch)
  1570.         }
  1571.         return decM;
  1572.     }
  1573.     catch(e)
  1574.     {
  1575.     }
  1576. }
  1577.  
  1578. function expK(encM)
  1579. {
  1580.     var cusK = orK;
  1581.     if(encM.length >= orK.length)
  1582.     {
  1583.         x = parseInt(encM.length/orK.length);
  1584.         cusK = "";
  1585.         for(var i=1;i<=x;i++)
  1586.         {
  1587.             cusK = cusK + orK;
  1588.         }
  1589.         if(encM.length-cusK.length > 0)
  1590.             cusK = cusK + cusK.slice(0,encM.length-cusK.length)
  1591.     }
  1592.     return cusK;
  1593. }
  1594.     
  1595. function checkForPhishing(pBl,url,dom_spec)
  1596. {
  1597.     try
  1598.     {
  1599.         var regExPB = pBl;
  1600.         if(regExPB)
  1601.         {
  1602.             var partRegEx = new Array();
  1603.             partRegEx=regExPB.split("\t");
  1604.             for(var m=0;m<partRegEx.length;m++)
  1605.             {
  1606.                 partRegEx[m] = dec(partRegEx[m]);
  1607.                 var execregex = new RegExp(customizePBLRegEx(partRegEx[m]))
  1608.                 var phish = execregex.exec(url)
  1609.                 if(phish==null)
  1610.                 {
  1611.                 }
  1612.                 else
  1613.                 {
  1614.                     //it is phishing---report phishing...
  1615.                     whitelistedDomains = getWhitelist();
  1616.                     var count = 0;
  1617.                     if (whitelistedDomains)
  1618.                     {
  1619.                         var whitelistedDomainsArray = whitelistedDomains.split(";");
  1620.                         count = whitelistedDomainsArray.length;
  1621.                     }
  1622.                     while (count--)
  1623.                     {
  1624.                         var item = whitelistedDomainsArray[count].toLowerCase();
  1625.                         var wldomain = url.toLowerCase().replace(/\./g,"\\.")
  1626.                         wldomain = wldomain.replace(/\//g,"\/");
  1627.                         var exp = new RegExp("^([^/]*\\.)?" + wldomain);
  1628.                         if (item.match(exp))
  1629.                         {
  1630.                             return false;
  1631.                         }
  1632.                         var found = is_whitelisted(dom_spec,item);
  1633.                         if(found)
  1634.                         {
  1635.                             return false;
  1636.                         }
  1637.                     }
  1638.                     var redirectURL = "http://www.siteadvisor.com/phishing.html?domain=" + stripargs(url) + "&reason=blacklist" + buildArgString();
  1639.                     window.content.location.replace(redirectURL);
  1640.                     return true;
  1641.                 }
  1642.             }
  1643.         }
  1644.     }
  1645.     catch(e)
  1646.     {
  1647.         //alert(e.message);
  1648.     }
  1649.     return false;
  1650. }
  1651.  
  1652. function customizePBLRegEx(inregex)
  1653. {
  1654.     try
  1655.     {
  1656.         var outregex = customizeRegEx(inregex);
  1657.         if(outregex.indexOf("(?i)")>=0)
  1658.             outregex =  outregex.slice(outregex.indexOf("(?i)") + 4 , outregex.length)
  1659.         return outregex;
  1660.     }
  1661.     catch(e)
  1662.     {
  1663.         //alert(e.message)
  1664.     }
  1665. }
  1666.  
  1667. var hd = [null, "^(.*[0-9]{1,3}[\-][0-9]{1,3}[\-][0-9]{1,3}[\-][0-9]{1,3}.*)$", "^(.*\.static\..*\.net.*)$", "^(.*\.adsl\..*)$", "^(.*\.customer\..*)$"];
  1668. var hp = "^(?:(?:(?:www)|(?:ftp))\.)*([a-zA-Z0-9][a-zA-Z0-9\-\._]+\/~[^\/?:&]+).*";
  1669.  
  1670. function SingleQueryDSSHandlerPriv(XML,loc) {
  1671.     checkForEmergency(XML);
  1672.  
  1673.     var domaininfo = XML.getElementsByTagName("DomainInfo");
  1674.     if (!domaininfo || !domaininfo.item(0)) {
  1675.         return;
  1676.     }
  1677.  
  1678.     domain_specifier = domaininfo.item(0).attributes.getNamedItem("name").nodeValue;
  1679.     popularity = domaininfo.item(0).attributes.getNamedItem("popularity").nodeValue.toLowerCase();
  1680.     
  1681.     var dmd = XML.getElementsByTagName("DomainMetaData");
  1682.     var regxp;
  1683.     if (dmd) {
  1684.         regxp = dmd.item(0).attributes.getNamedItem("domainSpecRegExs").nodeValue;
  1685.     } else {
  1686.         regxp = "REGEXNOTFOUND";
  1687.     }
  1688.     
  1689.     var firstReq=true;
  1690.     var secdssquery;
  1691.     if(regxp)
  1692.     {
  1693.         var myregex=regxp;
  1694.         var partRegEx = new Array();
  1695.         partRegEx=myregex.split(" ")
  1696.         for(var m=0;m<partRegEx.length;m++)
  1697.         {
  1698.             var execregex = new RegExp(customizeRegEx(partRegEx[m]))
  1699.             var found = execregex.exec(globalSloc)
  1700.             if(found==null)
  1701.             {
  1702.             }
  1703.             else
  1704.             {
  1705.                 if(found!=null)
  1706.                 {
  1707.                     if(found[1] && found[1].indexOf("/")>0)
  1708.                     {
  1709.                         globalSloc=found[1];
  1710.                         secdssquery = "Query?Entitlement=FOO&Type=domain&version=2&name="+escape(globalSloc)+"&client_ver="+getFullVersion()+"&locale="+getLocale()+"&aff_id="+getAffid();
  1711.                         firstReq=false;
  1712.                     }
  1713.                     if(found[1] && found[1].indexOf("/")<0)
  1714.                     {
  1715.                         var homepageRegEx = new RegExp(hp);
  1716.                         var foundHP = null;
  1717.                         var foundHP = homepageRegEx.exec(globalSloc);
  1718.                         if(foundHP)
  1719.                         {
  1720.                             var except = new RegExp(/\/~([^\/?:&]+)/);
  1721.                             var subdomain = except.exec(foundHP[1]);
  1722.                             var hn = extractHostName(globalSloc)
  1723.                             var hnComp = hn.split(".");
  1724.                             if(subdomain!="site" && subdomain!=hnComp[hnComp.length-2])
  1725.                             {
  1726.                                 globalSloc=foundHP[1];
  1727.                                 secdssquery = "Query?Entitlement=FOO&Type=domain&version=2&name="+escape(globalSloc)+"&client_ver="+getFullVersion()+"&locale="+getLocale()+"&aff_id="+getAffid();
  1728.                                 firstReq=false;
  1729.                             }
  1730.                         }
  1731.                         if(!foundHP)
  1732.                         {
  1733.                             var foundHD;
  1734.                             for(var iter=1;iter<5;iter++)
  1735.                             {
  1736.                                 var hostingDomainRegEx = new RegExp(hd[iter]);
  1737.                                 foundHD = hostingDomainRegEx.exec(extractHostName(globalSloc));
  1738.                                 if(foundHD)
  1739.                                 {
  1740.                                     globalSloc=foundHD[0]
  1741.                                     secdssquery = "Query?Entitlement=FOO&Type=domain&version=2&name="+escape(globalSloc)+"&client_ver="+getFullVersion()+"&locale="+getLocale()+"&aff_id="+getAffid();
  1742.                                     firstReq=false;
  1743.                                 }
  1744.                             }                                
  1745.                         }                        
  1746.                     }
  1747.                     break;
  1748.                 }
  1749.             }
  1750.         }        
  1751.     }
  1752.     if(firstReq==true)
  1753.     {
  1754.         try
  1755.         {
  1756.             var pBl = '';
  1757.             var phishingBlacklist = XML.getElementsByTagName("PhishingBlacklist");
  1758.             var pBl;
  1759.             for(var len = 0;len<phishingBlacklist[0].childNodes.length;len++)
  1760.             {
  1761.                 pBl = pBl + phishingBlacklist[0].childNodes.item(len).nodeValue;
  1762.             }
  1763.             var isPhish = checkForPhishing(pBl,loc,domain_specifier);
  1764.             if(isPhish) return;
  1765.         }
  1766.         catch(e)
  1767.         {
  1768.         }
  1769.         
  1770.         var classification = "";
  1771.  
  1772.         infochildren = domaininfo.item(0).childNodes;
  1773.         for (var i = 0; i < infochildren.length; i++) {
  1774.             if (infochildren.item(i).nodeName.toLowerCase() == "classification") {
  1775.  
  1776.                 classification = infochildren.item(i).attributes.getNamedItem("code").nodeValue.toLowerCase();
  1777.                 var color = infochildren.item(i).attributes.getNamedItem("color").nodeValue.toLowerCase();
  1778.                 if (classification == "unknown")
  1779.                     document.getElementById("SAFE-TB-Combined").setAttribute("image","chrome://safe/content/safe.gif");
  1780.                 else
  1781.                     document.getElementById("SAFE-TB-Combined").setAttribute("image","chrome://safe/content/safe-" + color + ".gif");
  1782.                 addToCache(domain_specifier, classification, color, popularity, regxp, pBl);
  1783.                 break;
  1784.             }
  1785.         }
  1786.  
  1787.         pingDSS();
  1788.  
  1789.         checkForRedirect(classification, popularity);
  1790.     }
  1791.     else
  1792.     {
  1793.         makeDssQuery(secdssquery,loc);    
  1794.     }
  1795. }
  1796.  
  1797. function retryDssQueryPriv(dssurl,dssquery,greq,forceSSL,loc) {
  1798.     if (dssurl.match(/dss1/)) dssurl = dssurl.replace("dss1","dss2");
  1799.     else if (dssurl.match(/dss2/)) dssurl = dssurl.replace("dss2","dss1");
  1800.     setDss(dssurl);
  1801.     httpGetRequest(dssurl, dssquery, false, false,greq,forceSSL);
  1802. }
  1803.  
  1804. function extractHostName(url)
  1805. {
  1806.     var idxDSlash = url.indexOf("//")
  1807.     if(idxDSlash > 0)
  1808.         url = url.slice(idxDSlash+2,url.length)
  1809.     var idxSSlash = url.indexOf("/")
  1810.     if(idxSSlash > 0)
  1811.         url = url.slice(0,idxSSlash)
  1812.     return url;
  1813. }
  1814.  
  1815. function customizeRegEx(inRegEx)
  1816. {
  1817.     var outRegEx = inRegEx.replace(/{/g,"(?:")
  1818.     outRegEx = outRegEx.replace(/}/g,")")
  1819.     return outRegEx;
  1820. }
  1821.  
  1822. function SingleQueryDSSHandler(XML,loc) {
  1823.     checkForEmergency(XML);
  1824.  
  1825.     var domaininfo = XML.getElementsByTagName("DomainInfo");
  1826.     if (!domaininfo || !domaininfo.item(0)) {
  1827.         return;
  1828.     }
  1829.  
  1830.     domain_specifier = domaininfo.item(0).attributes.getNamedItem("name").nodeValue;
  1831.     popularity = domaininfo.item(0).attributes.getNamedItem("popularity").nodeValue.toLowerCase();
  1832.     var dmd = XML.getElementsByTagName("DomainMetaData");
  1833.     var regxp;
  1834.     if (dmd) {
  1835.         regxp = dmd.item(0).attributes.getNamedItem("domainSpecRegExs").nodeValue;
  1836.     } else {
  1837.         regxp = "REGEXNOTFOUND";
  1838.     }
  1839.  
  1840.     try
  1841.     {
  1842.         var pBl = '';
  1843.         var phishingBlacklist = XML.getElementsByTagName("PhishingBlacklist");
  1844.         var pBl;
  1845.         for(var len = 0;len<phishingBlacklist[0].childNodes.length;len++)
  1846.         {
  1847.             pBl = pBl + phishingBlacklist[0].childNodes.item(len).nodeValue;
  1848.         }
  1849.         var isPhish = checkForPhishing(pBl,loc,domain_specifier);
  1850.         if(isPhish) return;
  1851.     }
  1852.     catch(e)
  1853.     {
  1854.     }
  1855.     
  1856.     var classification = "";
  1857.  
  1858.     infochildren = domaininfo.item(0).childNodes;
  1859.     for (var i = 0; i < infochildren.length; i++) {
  1860.         if (infochildren.item(i).nodeName.toLowerCase() == "classification") {
  1861.  
  1862.             classification = infochildren.item(i).attributes.getNamedItem("code").nodeValue.toLowerCase();
  1863.             var color = infochildren.item(i).attributes.getNamedItem("color").nodeValue.toLowerCase();
  1864.  
  1865.             if (classification == "unknown")
  1866.                 document.getElementById("SAFE-TB-Combined").setAttribute("image","chrome://safe/content/safe.gif");
  1867.             else
  1868.                 document.getElementById("SAFE-TB-Combined").setAttribute("image","chrome://safe/content/safe-" + color + ".gif");
  1869.             addToCache(domain_specifier, classification, color, popularity, regxp, pBl);
  1870.             break;
  1871.         }
  1872.     }
  1873.  
  1874.     pingDSS();
  1875.  
  1876.     checkForRedirect(classification, popularity);
  1877. }
  1878.  
  1879.  
  1880. function focus_handler(e) {
  1881.     if (e.originalTarget.nodeName == "#document" || e.originalTarget.nodeName == "tab" || e.originalTarget.nodeName == "xul:tab") {
  1882.         docloc = window._content.document.location.href;
  1883.         if (docloc != loc) {
  1884.             changebutton();
  1885.         }
  1886.     }
  1887. }
  1888.  
  1889. function openSettings() {
  1890.     window.openDialog('chrome://safe/content/settings.xul','safe-settings','chrome,modal',
  1891.         getPremium(), getButtonEnabled(), getSafeOn(), getHighlight(), getSSL());
  1892.  
  1893.     nav_href = window._content.document.location.href;
  1894.  
  1895.     buttonon = getButtonEnabled();
  1896.     on = getSafeOn();
  1897.     highliteon = getHighlight();
  1898.     doSSL = getSSL();
  1899.  
  1900.     if (!buttonon) {
  1901.         document.getElementById("SAFE-TB-Combined").setAttribute("image","chrome://safe/content/safe.gif");
  1902.     } else {
  1903.         changebutton();
  1904.     }
  1905.     if (params.ok && eval(on_search_page) == true) {
  1906.         window._content.location.reload();
  1907.     }
  1908. }
  1909.  
  1910. function writeSettings() {
  1911.     if (!premium)
  1912.         setButtonEnabled(document.getElementById("button").checked);
  1913.     setSafeOn(document.getElementById("on").checked);
  1914.     setHighlight(document.getElementById("highlight").checked);
  1915.     setSSL(document.getElementById("ssl").checked);
  1916. }
  1917.  
  1918. function whitelist() {
  1919.     window.openDialog('chrome://safe/content/whitelist.xul', 'safe-whitelist',
  1920.                         'chrome,modal', getPremium(), domain_specifier, getWhitelist());
  1921.     whitelistedDomains = getWhitelist();
  1922. }
  1923.  
  1924. function urlToDomain(url)
  1925. {
  1926.     var hostName = extractHostName(url);
  1927.     var hostNameComp = new Array();
  1928.     hostNameComp = hostName.split(".");
  1929.     var compLen = hostNameComp.length - 1;
  1930.     var domain;
  1931.     if (hostNameComp[compLen].length <= 2 && hostNameComp[compLen - 1].length <= 3)
  1932.     {
  1933.         for(var i=0;i<2;i++)
  1934.         {
  1935.             try
  1936.             {
  1937.                 domain = hostNameComp[compLen - i] + domain;
  1938.             }
  1939.             catch(e)
  1940.             {
  1941.                 break;
  1942.             }
  1943.         }
  1944.     }
  1945.     else
  1946.     {
  1947.         for(var i=0;i<1;i++)
  1948.         {
  1949.             try
  1950.             {
  1951.                 domain = hostNameComp[compLen - i] + domain;
  1952.             }
  1953.             catch(e)
  1954.             {
  1955.                 break;
  1956.             }
  1957.         }
  1958.     }
  1959.     domain = domain.toLowerCase();
  1960.     return domain;
  1961. }
  1962.  
  1963. function addWhitelist(url)
  1964. {
  1965.     try
  1966.     {
  1967.         var whitelistedDomains = getWhitelist();
  1968.         var whArray = whitelistedDomains.split(";");
  1969.         for(var idx=0;idx<whArray.length;idx++)
  1970.         {
  1971.             if(whArray[idx] == url)
  1972.                 return;
  1973.         }
  1974.         whitelistedDomains = whitelistedDomains + ";" + url;
  1975.         setWhitelist(whitelistedDomains);
  1976.     }
  1977.     catch(e)
  1978.     {
  1979.         //alert(e.message)
  1980.     }
  1981. }
  1982.  
  1983. function updateWhitelist() {
  1984.     whitelistedDomains = "";
  1985.     var list = document.getElementById('SAFE-whitelist');
  1986.     var count = list.getRowCount();
  1987.     while (count--)
  1988.     {
  1989.         var item = list.getItemAtIndex(count);
  1990.         var itemlabel = item.label.replace( /^\s+/g, "" ).replace( /\s+$/g, "" );
  1991.  
  1992.         if (itemlabel.length > 0)
  1993.             whitelistedDomains = whitelistedDomains + itemlabel + ";";
  1994.     }
  1995.  
  1996.      setWhitelist(whitelistedDomains);
  1997. }
  1998.  
  1999. function setWhitelist(value)
  2000. {
  2001.     try
  2002.     {
  2003.         var interface = getSaXPCom();
  2004.         if(getWhitelist())
  2005.             interface.RemoveWhitelistSites(getWhitelist())
  2006.         interface.AddWhitelistSites(value);
  2007.     }
  2008.     catch(err)
  2009.     {
  2010.         var pref = setCharPref("extensions.safe.whitelist", value);
  2011.         return pref;
  2012.     }
  2013. }
  2014.  
  2015. function setEnable (enable) {
  2016.     buttonon = enable;
  2017.  
  2018.     setButtonEnabled(enable)
  2019.     changebutton();
  2020. }
  2021.  
  2022. function setPSurf (enable) {
  2023.     if (!enable) {
  2024.         if(navigator.userAgent.match(/Windows NT 6.0/gi))
  2025.         {
  2026.             if(navigator.language.match(/ja/))
  2027.                 window.openDialog('chrome://safe/content/password.xul', 'safe-password', 'chrome,modal', getHint(), "400px");
  2028.             else
  2029.                 window.openDialog('chrome://safe/content/password.xul', 'safe-password', 'chrome,modal', getHint(), "350px");
  2030.         }
  2031.         else
  2032.             window.openDialog('chrome://safe/content/password.xul', 'safe-password', 'chrome,modal', getHint(), "350px");
  2033.     } else {
  2034.         if (!getPsurfInitialized())
  2035.             if(navigator.userAgent.match(/Windows NT 6.0/gi))
  2036.             {
  2037.                 if(navigator.language.match(/ja/))
  2038.                     window.openDialog('chrome://safe/content/setpassword.xul','safe-setpassword','chrome,modal',"400px");
  2039.                 else
  2040.                     window.openDialog('chrome://safe/content/setpassword.xul','safe-setpassword','chrome,modal',"350px");
  2041.             }
  2042.             else
  2043.                 window.openDialog('chrome://safe/content/setpassword.xul','safe-setpassword','chrome,modal',"350px");
  2044.         else {
  2045.              try {
  2046.                  var interface = getSaXPCom();
  2047.  
  2048.                 setEnable(true);
  2049.                  interface.SetRestrictedMode("Restricted");
  2050.                 setBoolPref("extensions.safe.flag",false);
  2051.              } catch(err) {
  2052.                  alert("Failed to set restrited mode.");
  2053.              }
  2054.         }
  2055.     }
  2056. }
  2057.  
  2058. function validatePassword() {
  2059.     var password = document.getElementById('SAFE-password-text').value;
  2060.      try {
  2061.          var interface = getSaXPCom();
  2062.  
  2063.          if (interface.PasswordMatches(password)) {
  2064.              interface.SetRestrictedMode("Unrestricted:" + password);
  2065.             setBoolPref("extensions.safe.flag",true);
  2066.              return;
  2067.          }
  2068.      } catch(err) {
  2069.          alert("Failed to validate password.");
  2070.      }
  2071.  
  2072.     window.openDialog('chrome://safe/content/badpassword.xul','safe-badpassword','chrome,modal');
  2073.     return false;
  2074. }
  2075.  
  2076. function checkPassword() {
  2077.     var password = document.getElementById('SAFE-enter-password').value;
  2078.     var password2 = document.getElementById('SAFE-enter-password2').value;
  2079.     var hint = document.getElementById('SAFE-enter-hint').value;
  2080.  
  2081.     if ((password.length > 0) && (password == password2)) {
  2082.          try {
  2083.              var interface = getSaXPCom();
  2084.  
  2085.             setEnable(true);
  2086.              interface.SetRestrictedMode("Password:" + password + ":" + hint);
  2087.              interface.SetRestrictedMode("Restricted");
  2088.             setBoolPref("extensions.safe.flag",false);        
  2089.          } catch(err) {
  2090.              alert("Failed to set password.");
  2091.          }
  2092.         return true;
  2093.     }
  2094.  
  2095.     window.openDialog('chrome://safe/content/mismatchpassword.xul','safe-mismatchpassword','chrome,modal');
  2096.     return false;
  2097. }
  2098.  
  2099. function getGuid()
  2100. {
  2101.     try
  2102.     {
  2103.         var interface = getSaXPCom();
  2104.         return interface.GetGuid();
  2105.     }
  2106.     catch(e)
  2107.     {
  2108.         return getUuid();
  2109.     }
  2110. }
  2111.  
  2112. function getUuid()
  2113. {
  2114.     return getCharPref("extensions.safe.uuid",readUuid());
  2115. }
  2116.  
  2117. function readUuid()
  2118. {
  2119.     try
  2120.     {
  2121.         var myfile = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
  2122.  
  2123.         if(navigator.userAgent.match(/Windows NT 6.0/gi))
  2124.         {
  2125.             var file = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get("DrvD", Components.interfaces.nsIFile);
  2126.             myfile.initWithPath(file.path + "\\ProgramData\\SiteAdvisor\\guid.txt");
  2127.         }
  2128.         else
  2129.         {
  2130.             if(navigator.userAgent.match(/Windows/gi))
  2131.             {
  2132.                 var file = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get("AppData", Components.interfaces.nsIFile);
  2133.                 var fp = file.path;
  2134.                 var find = fp.match(/[^:]\\/);
  2135.                 var fp_new = fp.slice(0,find.index+1);
  2136.  
  2137.                 myfile.initWithPath(fp_new + "\\All Users\\Application Data\\SiteAdvisor\\guid.txt");
  2138.             }
  2139.         }
  2140.  
  2141.         if(navigator.userAgent.match(/Windows/gi))
  2142.         {
  2143.             if(!myfile.exists())
  2144.             {
  2145.                 var charset = "ISO-8859-1";
  2146.                 var os = Components.classes["@mozilla.org/intl/converter-output-stream;1"].createInstance(Components.interfaces.nsIConverterOutputStream);
  2147.                 var fos = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);
  2148.  
  2149.                 fos.init(myfile, 0x02 | 0x08 | 0x20, 0664, 0);
  2150.                 os.init(fos, charset, 0, 0x0000);
  2151.                 var uuidString = setUuid();
  2152.                 os.writeString(uuidString);
  2153.                 return uuidString;
  2154.             }
  2155.             else
  2156.             {
  2157.                 var uuidString = "";
  2158.                 var fstream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream);
  2159.                 var sstream = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream);
  2160.                 fstream.init(myfile, 1, 0, false);
  2161.                 sstream.init(fstream);
  2162.                 var str = sstream.read(-1);
  2163.                 while (str.length > 0)
  2164.                 {
  2165.                     uuidString += str;
  2166.                     str = sstream.read(-1);
  2167.                 }
  2168.                 sstream.close();
  2169.                 fstream.close();
  2170.                 return uuidString;
  2171.             }
  2172.         }
  2173.         else
  2174.         {
  2175.             var uuidString = setUuid();
  2176.             return uuidString;
  2177.         }
  2178.     }
  2179.     catch(e)
  2180.     {
  2181.         var uuidString = setUuid();
  2182.         return uuidString;    
  2183.     }
  2184. }
  2185.  
  2186. function setUuid()
  2187. {
  2188.     try
  2189.     {
  2190.         var uuidGenerator = Components.classes["@mozilla.org/uuid-generator;1"].getService(Components.interfaces.nsIUUIDGenerator);
  2191.         var uuid = uuidGenerator.generateUUID();
  2192.         var uuidString = uuid.toString();
  2193.         var idxOpen = uuidString.indexOf("{");
  2194.         var idxClose = uuidString.indexOf("}");
  2195.         uuidString = uuidString.substring(idxOpen+1,idxClose);
  2196.         return uuidString;
  2197.     }
  2198.     catch(err)
  2199.     {
  2200.         //convert it to similar form
  2201.         var uuidString = '';
  2202.         while(true)
  2203.         {
  2204.             var theTime = new Date();
  2205.             var num1 = Math.round(Math.random() * theTime);
  2206.             var uuidString = uuidString + num1.toString();
  2207.             if (uuidString.length>32) break;
  2208.         }
  2209.         uuidString = uuidString.slice(0,32);
  2210.         uuidString = uuidString.slice(0,8) + "-" + uuidString.slice(8,12) + "-" + uuidString.slice(12,16) + "-" + uuidString.slice(16,20) + "-" + uuidString.slice(20,32);
  2211.         return uuidString;
  2212.     }
  2213. }
  2214.  
  2215. function postInstallCheck() {
  2216.     var firstInstall = getBoolPref("extensions.safe.firstinstall", true);
  2217.     var machPolicyUpdate = getIntPref("extensions.{1650a312-02bc-40ee-977e-83f158701739}.PolicyUpdate",0);
  2218.     var userPolicyUpdate = getIntPref("extensions.safe.PolicyUpdate",0);
  2219.  
  2220.     if (firstInstall) {
  2221.         var params = {ok:false};
  2222.  
  2223.         setBoolPref("extensions.safe.firstinstall",false);
  2224.         setIntPref("extensions.safe.PolicyUpdate",machPolicyUpdate);        
  2225.         window.openDialog('chrome://safe/content/disclosure.xul','safe-disclosure','chrome,modal',params);
  2226.         if (params.ok) {
  2227.             try {
  2228.                 window._content.location.href = "http://www.siteadvisor.com/download/ff_postinstall.html?aff_id="+getAffid();
  2229.                        var irequest = new XMLHttpRequest();
  2230.                 var pingquery = checkSSL(getDss()) + "Ping?Version=2&Type=install&client_type=SAFE&client_ver=" + getFullVersion() + "&locale="+getLocale()+"&aff_id="+getAffid() + "&UID="+getGuid();
  2231.                     irequest.open("GET", pingquery, true);
  2232.                     irequest.send(null);
  2233.             } catch (comerr) {}
  2234.             addSASearch();
  2235.             if (getPremium()) {
  2236.                 setPSurf(true);
  2237.             }
  2238.         } else {
  2239.             removeInstallRegKey();
  2240.             setBoolPref("extensions.safe.firstinstall",true);
  2241.             setIntPref("extensions.safe.PolicyUpdate",machPolicyUpdate);
  2242.             var gExtensionManager = Components.classes["@mozilla.org/extensions/manager;1"].getService(Components.interfaces.nsIExtensionManager);
  2243.             try {
  2244.                 gExtensionManager.uninstallItem("{1650a312-02bc-40ee-977e-83f158701739}");
  2245.             } catch (e) {
  2246.                 ds = gExtensionManager.datasource;
  2247.                 gExtensionManager.uninstallExtension("{1650a312-02bc-40ee-977e-83f158701739}");
  2248.             }
  2249.             window.openDialog('chrome://safe/content/uninst.xul','safe-uninst','chrome,modal');
  2250.         }
  2251.     }
  2252.     if(machPolicyUpdate>userPolicyUpdate && !firstInstall)
  2253.     {
  2254.         window.openDialog('chrome://safe/content/ppnotification.xul','safe-ppnotification','chrome,modal');
  2255.         setIntPref("extensions.safe.PolicyUpdate",machPolicyUpdate);
  2256.     }
  2257. }
  2258.  
  2259. function removeInstallRegKey() {
  2260.   try {
  2261.     var regKey = Components.classes["@mozilla.org/windows-registry-key;1"].createInstance(Components.interfaces.nsIWindowsRegKey);
  2262.  
  2263.     regKey.open(Components.interfaces.nsIWindowsRegKey.ROOT_KEY_LOCAL_MACHINE, "SOFTWARE\\Mozilla\\Firefox\\Extensions", Components.interfaces.nsIWindowsRegKey.ACCESS_WRITE);
  2264.     regKey.removeValue("{1650a312-02bc-40ee-977e-83f158701739}");
  2265.     regKey.close ();
  2266.   } catch (RegErr) {}
  2267.  
  2268.   try {
  2269.     var regKey = Components.classes["@mozilla.org/windows-registry-key;1"].createInstance(Components.interfaces.nsIWindowsRegKey);
  2270.  
  2271.     regKey.open(Components.interfaces.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER, "SOFTWARE\\Mozilla\\Firefox\\Extensions", Components.interfaces.nsIWindowsRegKey.ACCESS_WRITE);
  2272.     regKey.removeValue("{1650a312-02bc-40ee-977e-83f158701739}");
  2273.     regKey.close ();
  2274.   } catch (RegErr) {}
  2275. }
  2276.  
  2277. function countWindows() {
  2278.     var wm = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService(Components.interfaces.nsIWindowMediator);
  2279.     en = wm.getEnumerator("");
  2280.     var n = 0;
  2281.  
  2282.     while (en.hasMoreElements()) {
  2283.         var w = en.getNext();
  2284.         if (w.document.getElementById("content") && w.document.getElementById("content").tagName == "tabbrowser") {
  2285.             var b = w.document.getElementById("content");
  2286.             var ntabs = b.mPanelContainer.childNodes.length;
  2287.  
  2288.             n = n + ntabs;
  2289.         }
  2290.         n++;
  2291.     }
  2292.  
  2293.     return n;
  2294. }
  2295.  
  2296. function cleanup() {
  2297.     if (byebye == true) {
  2298.         var pingquery = checkSSL(getDss()) + "Ping?Version=2&Type=uninstall&client_type=SAFE&client_ver=" + getFullVersion()+"&locale="+getLocale()+"&aff_id="+getAffid()+"&UID="+getGuid();
  2299.         var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
  2300.         pref.clearUserPref("extensions.safe.build");
  2301.         pref.clearUserPref("extensions.safe.dss");
  2302.         pref.clearUserPref("extensions.safe.firstinstall");
  2303.         pref.clearUserPref("extensions.safe.highlight");
  2304.         pref.clearUserPref("extensions.safe.lastDailyPing");
  2305.         pref.clearUserPref("extensions.safe.lastMonthlyPing");
  2306.         pref.clearUserPref("extensions.safe.on");
  2307.         pref.clearUserPref("extensions.safe.enablebutton");
  2308.         pref.clearUserPref("extensions.safe.lastKnownVersion");
  2309.         pref.clearUserPref("extensions.safe.doSSL");
  2310.         pref.clearUserPref("extensions.safe.whitelist");
  2311.         pref.clearUserPref("extensions.safe.PolicyUpdate");
  2312.         try
  2313.         {
  2314.             pref.clearUserPref("extensions.safe.flag");
  2315.         }
  2316.         catch(e)
  2317.         {
  2318.         }
  2319.         removeSASearch();
  2320.         removeInstallRegKey();
  2321.         try{
  2322.                var irequest = new XMLHttpRequest();
  2323.             irequest.open("GET", pingquery, false);
  2324.             irequest.send(null);
  2325.         } catch (reqerr) {}
  2326.             return;
  2327.     }
  2328.  
  2329.     var windowCount = countWindows();
  2330.     if (windowCount == 0) {
  2331.         setButtonEnabled(true);
  2332.     }
  2333.  
  2334.     var RDFService = Components.classes["@mozilla.org/rdf/rdf-service;1"].getService(Components.interfaces.nsIRDFService);
  2335.     var Container = Components.classes["@mozilla.org/rdf/container;1"].getService(Components.interfaces.nsIRDFContainer);
  2336.     var extensionDS= Components.classes["@mozilla.org/extensions/manager;1"].getService(Components.interfaces.nsIExtensionManager).datasource;
  2337.     try {
  2338.         var root = RDFService.GetResource("urn:mozilla:item:root");
  2339.         Container.Init(extensionDS,root);
  2340.     } catch (e) {
  2341.         var root = RDFService.GetResource("urn:mozilla:extension:root");
  2342.         Container.Init(extensionDS,root);
  2343.     }
  2344.     var nameArc = RDFService.GetResource("http://www.mozilla.org/2004/em-rdf#name");
  2345.     var toBeUninstalledArc = RDFService.GetResource("http://www.mozilla.org/2004/em-rdf#toBeUninstalled");
  2346.  
  2347.     var found = false;
  2348.     var elements = Container.GetElements();
  2349.     while (elements.hasMoreElements()) {
  2350.            var element = elements.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
  2351.            var name;
  2352.            var toBeUninstalled;
  2353.  
  2354.            var target = extensionDS.GetTarget(element, nameArc ,true);
  2355.            if (target) {
  2356.                name = target.QueryInterface(Components.interfaces.nsIRDFLiteral).Value;
  2357.  
  2358.            if (name == "McAfee SiteAdvisor") {
  2359.                target = extensionDS.GetTarget(element, toBeUninstalledArc ,true);
  2360.                if (target) {
  2361.                    toBeUninstalled=target.QueryInterface(Components.interfaces.nsIRDFLiteral).Value;
  2362.                 if (toBeUninstalled && (toBeUninstalled == "true")) {
  2363.                     window.removeEventListener("unload", cleanup, false);
  2364.                     var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
  2365.                     var pingquery = checkSSL(getDss()) + "Ping?Version=2&Type=uninstall&client_type=SAFE&client_ver=" + getFullVersion()+"&locale="+getLocale()+"&aff_id="+getAffid()+"&UID="+getGuid();
  2366.                     var oldaffid = getAffid();
  2367.                     pref.clearUserPref("extensions.safe.build");
  2368.                     pref.clearUserPref("extensions.safe.dss");
  2369.                     pref.clearUserPref("extensions.safe.firstinstall");
  2370.                     pref.clearUserPref("extensions.safe.highlight");
  2371.                     pref.clearUserPref("extensions.safe.lastDailyPing");
  2372.                     pref.clearUserPref("extensions.safe.lastMonthlyPing");
  2373.                     pref.clearUserPref("extensions.safe.on");
  2374.                     pref.clearUserPref("extensions.safe.enablebutton");
  2375.                     pref.setBoolPref("extensions.safe.uninstalled",true);
  2376.                     pref.clearUserPref("extensions.safe.lastKnownVersion");
  2377.                        pref.clearUserPref("extensions.safe.doSSL");
  2378.                     pref.clearUserPref("extensions.safe.whitelist");
  2379.                     pref.clearUserPref("extensions.safe.PolicyUpdate");
  2380.                     try
  2381.                     {
  2382.                         pref.clearUserPref("extensions.safe.flag");
  2383.                     }
  2384.                     catch(e)
  2385.                     {
  2386.                     }
  2387.                     removeSASearch();
  2388.                        removeInstallRegKey();
  2389.                     try {
  2390.                         var irequest = new XMLHttpRequest();
  2391.                         irequest.open("GET", pingquery, false);
  2392.                         irequest.send(null);
  2393.                     } catch(reqerr) {}
  2394.                     window.open("http://www.siteadvisor.com/ffuninstall.html?aff_id="+oldaffid);
  2395.                 }
  2396.             }
  2397.             break;
  2398.            }
  2399.         }
  2400.     }
  2401. }
  2402.  
  2403. var uninstallObserver = {
  2404.   observe: function(aSubject, aTopic, aData)
  2405.   {
  2406.     try {
  2407.         item = aSubject.QueryInterface(Components.interfaces.nsIUpdateItem);
  2408.         if (item.id != "{1650a312-02bc-40ee-977e-83f158701739}") return;
  2409.         if (aData == "item-uninstalled"){
  2410.             byebye = true;
  2411.             var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
  2412.  
  2413.             var firstInstall = false;
  2414.             try{
  2415.                 firstInstall =  pref.getBoolPref("extensions.safe.firstinstall");
  2416.             } catch(ein) {}
  2417.  
  2418.             if (!firstInstall) {
  2419.                 pref.setBoolPref("extensions.safe.uninstalled",true);
  2420.                 window.open("http://www.siteadvisor.com/ffuninstall.html?aff_id="+getAffid());
  2421.             }
  2422.         }
  2423.     } catch (e) {}
  2424.   }
  2425. };
  2426.  
  2427.  
  2428. function addUninstallObserver() {
  2429.   var obs = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces["nsIObserverService"]);
  2430.   obs.addObserver(uninstallObserver, "em-action-requested", false);
  2431. }
  2432.  
  2433. function removeSASearch() {
  2434.   try{
  2435.  
  2436.     var file = Components.classes["@mozilla.org/file/directory_service;1"]
  2437.                      .getService(Components.interfaces.nsIProperties)
  2438.                      .get("ProfD", Components.interfaces.nsIFile);
  2439.     file.append("searchplugins");
  2440.     file.append("siteadvisor.src");
  2441.  
  2442.     file.remove(false);
  2443.     file = Components.classes["@mozilla.org/file/directory_service;1"]
  2444.                      .getService(Components.interfaces.nsIProperties)
  2445.                      .get("ProfD", Components.interfaces.nsIFile);
  2446.     file.append("searchplugins");
  2447.     file.append("siteadvisor.gif");
  2448.  
  2449.     file.remove(false);
  2450.   } catch (e) {
  2451.     try{
  2452.         var file = Components.classes["@mozilla.org/file/directory_service;1"]
  2453.                      .getService(Components.interfaces.nsIProperties)
  2454.                      .get("CurProcD", Components.interfaces.nsIFile);
  2455.         file.append("searchplugins");
  2456.         file.append("siteadvisor.src");
  2457.  
  2458.         file.remove(false);
  2459.         file = Components.classes["@mozilla.org/file/directory_service;1"]
  2460.                      .getService(Components.interfaces.nsIProperties)
  2461.                      .get("ProfD", Components.interfaces.nsIFile);
  2462.         file.append("searchplugins");
  2463.         file.append("siteadvisor.gif");
  2464.  
  2465.         file.remove(false);
  2466.     } catch (e2) {}
  2467.   }
  2468. }
  2469.  
  2470. function addSASearch() {
  2471.     var internetSearch = Components.classes["@mozilla.org/browser/internetsearch-service;1"].getService(Components.interfaces.nsIInternetSearchService);
  2472.     internetSearch.AddSearchEngine("http://www.siteadvisor.com/download/safe/siteadvisor.src", "http://www.siteadvisor.com/download/safe/siteadvisor.gif", "","");
  2473.  
  2474.     setEnable(true);
  2475. }
  2476.  
  2477. function checkForEmergency(xml) {
  2478.     if (alreadyWarned) return;
  2479.     var urr = xml.getElementsByTagName("UpgradeRequiredResponse");
  2480.     if (urr.length == 0) return;
  2481.     urr = urr[0].childNodes;
  2482.     for (var i = 0; i < urr.length; i++) {
  2483.         var c = urr.item(i);
  2484.         if (c.nodeName.toLowerCase() == "description") {
  2485.             alert(c.firstChild.nodeValue);
  2486.             alreadyWarned = true;
  2487.         }
  2488.     }
  2489. }
  2490.  
  2491. function getAffid() {
  2492.   try {
  2493.     var affid = OEMstrb("Affid");
  2494.     if (affid) return affid;
  2495.   } catch (StrBErr) {}
  2496.   return 0;
  2497. }
  2498.  
  2499. function hasSuite() {
  2500.   try {
  2501.     var regKey = Components.classes["@mozilla.org/windows-registry-key;1"].createInstance(Components.interfaces.nsIWindowsRegKey);
  2502.     regKey.open(Components.interfaces.nsIWindowsRegKey.ROOT_KEY_LOCAL_MACHINE, "SOFTWARE\\SiteAdvisor", Components.interfaces.nsIWindowsRegKey.ACCESS_READ);
  2503.     var hasSuite = regKey.readStringValue("HasSuite");
  2504.     if (hasSuite == "true") return true;
  2505.   } catch(regErr) {}
  2506.  
  2507.   return false;
  2508. }
  2509.  
  2510. function getShowUpsellMessage() {
  2511.   try {
  2512.     var showUpsellMessage = OEMstrb("ShowSafeSearchUpsell");
  2513.     if (showUpsellMessage && showUpsellMessage.toLowerCase() == "true") return true;
  2514.     else if (showUpsellMessage && showUpsellMessage.toLowerCase() == "false") return false;
  2515.   } catch (StrBErr) {}
  2516.  
  2517.   if (hasSuite())
  2518.       return false;
  2519.  
  2520.   return true;
  2521. }
  2522.  
  2523. function getUpsellMessage() {
  2524.   try {
  2525.     var upsellMessage = OEMstrb("SafeSearchUpsellMessage");
  2526.     if (upsellMessage) return upsellMessage;
  2527.   } catch (StrBErr) {}
  2528.   return strb('safe.submitError');
  2529. }
  2530.  
  2531. function getUpsellUrl() {
  2532.   try {
  2533.     var upsellUrl = OEMstrb("SafeSearchUpsellUrl");
  2534.     if (upsellUrl) return upsellUrl;
  2535.   } catch (StrBErr) {}
  2536.   return null;
  2537. }
  2538.  
  2539. function getShowMenuUpsellMessage() {
  2540.   try {
  2541.     var showMenuUpsellMessage = OEMstrb("ShowMenuUpsell");
  2542.     if (showMenuUpsellMessage && showMenuUpsellMessage.toLowerCase() == "true") return true;
  2543.     else if (showMenuUpsellMessage && showMenuUpsellMessage.toLowerCase() == "false") return false;
  2544.   } catch (StrBErr) {}
  2545.  
  2546.   if (hasSuite())
  2547.       return false;
  2548.  
  2549.   return false;
  2550. }
  2551.  
  2552. function getMenuUpsellMessage() {
  2553.   try {
  2554.     var upsellMessage = OEMstrb("MenuUpsellMessage");
  2555.     if (upsellMessage) return upsellMessage;
  2556.   } catch (StrBErr) {}
  2557.   return strb('safe.submitError');
  2558. }
  2559.  
  2560. function getMenuUpsellUrl() {
  2561.   try {
  2562.     var upsellUrl = OEMstrb("MenuUpsellUrl");
  2563.     if (upsellUrl) return upsellUrl;
  2564.   } catch (StrBErr) {}
  2565.   return null;
  2566. }
  2567.  
  2568. function setUpdateURL() {
  2569.     var updateON = OEMstrb('AutoUpdateFF');
  2570.     if (!updateON) updateON = "true";
  2571.     try {
  2572.         if (updateON == "false")
  2573.           setCharPref("extensions.{1650a312-02bc-40ee-977e-83f158701739}.updateURL","");
  2574.         else
  2575.           setCharPref("extensions.{1650a312-02bc-40ee-977e-83f158701739}.updateURL","https://sadownload.mcafee.com/products/sa/firefox/update.rdf?aff_id="+getAffid());
  2576.     } catch (prefErr) {}
  2577. }
  2578.  
  2579. function getPhishOn() {
  2580.     try {
  2581.         var phishON = OEMstrb('AntiPhishing');
  2582.         if (phishON && (phishON == "false")) return false;
  2583.     } catch (prefErr) {}
  2584.  
  2585.     return true;
  2586. }
  2587.  
  2588. function strb(strKey) {
  2589.   try{
  2590.     return document.getElementById('safe-script-bundle').getString(strKey);
  2591.   } catch (bundleErr) {
  2592.     return null;
  2593.   }
  2594. }
  2595.  
  2596. function OEMstrb(strKey) {
  2597.   try {
  2598.     return OEMStrB.GetStringFromName(navigator.language+"."+strKey);
  2599.   } catch (bundleErr) {}
  2600.   try {
  2601.     return OEMStrB.GetStringFromName(navigator.language.toLowerCase()+"."+strKey);
  2602.   } catch (bundleErr) {}
  2603.   try {
  2604.     return OEMStrB.GetStringFromName(strKey);
  2605.   } catch (bundleErr) {}
  2606.   return null;
  2607. }
  2608.  
  2609. function chromeExists(p) {
  2610.   try {
  2611.     var chromeRegistry = Components.classes["@mozilla.org/chrome/chrome-registry;1"].getService(Components.interfaces.nsIChromeRegistry);
  2612.     var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
  2613.     var chromeFileURI = ioService.newURI(p,"UTF-8",null);
  2614.     var localFileURI = chromeRegistry.convertChromeURL(chromeFileURI);
  2615.     if (localFileURI.spec.match(/^jar:/)) {
  2616.       var jarFile = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
  2617.       var jarPath = localFileURI.spec.split("!")[0].replace(/jar:/,"");
  2618.       jarPath = ioService.getProtocolHandler("file").QueryInterface(Components.interfaces.nsIFileProtocolHandler).getFileFromURLSpec(jarPath).path;
  2619.       jarFile.initWithPath(jarPath);
  2620.       var relPath = localFileURI.spec.split("!")[1].replace(/^\//, "");
  2621.       var zipReader = Components.classes["@mozilla.org/libjar/zip-reader;1"].createInstance(Components.interfaces.nsIZipReader);
  2622.       zipReader.init(jarFile);
  2623.       zipReader.open();
  2624.       var found = zipReader.findEntries(relPath);
  2625.       var result = found ? found.hasMoreElements() : false;
  2626.       zipReader.close();
  2627.       return result;
  2628.     } else {
  2629.       var localFile = ioService.getProtocolHandler("file").QueryInterface(Components.interfaces.nsIFileProtocolHandler).getFileFromURLSpec(localFileURI.spec);
  2630.       return localFile.exists();
  2631.     }
  2632.   } catch (chromeErr) {
  2633.     return false;
  2634.   }
  2635. }
  2636.  
  2637. function getMode()
  2638. {
  2639.     if(getSaXPCom())
  2640.     {
  2641.     }
  2642.     else
  2643.     {
  2644.         return BASIC;
  2645.     }
  2646.     
  2647.     var saPlus;
  2648.     try
  2649.     {
  2650.         saPlus = OEMstrb('saPlusOnly').toLowerCase();
  2651.     }
  2652.     catch(e)
  2653.     {
  2654.         saPlus = "false";
  2655.     }
  2656.     
  2657.     var saSub = getPremium();
  2658.     if(saPlus=="true" && saSub)
  2659.     {
  2660.         return PLUS;
  2661.     }
  2662.     else
  2663.     {
  2664.         if(saPlus=="true" && !saSub)
  2665.         {
  2666.             return CRIPPLED;
  2667.         }
  2668.         else
  2669.         {
  2670.             if(saPlus=="false" && saSub)
  2671.             {
  2672.                 return PLUS;
  2673.             }
  2674.             else
  2675.             {
  2676.                 if(saPlus=="false" && !saSub)
  2677.                 {
  2678.                     return BASIC;
  2679.                 }
  2680.             }
  2681.         }
  2682.     }
  2683. }
  2684.  
  2685. function setCrippled()
  2686. {
  2687.     try
  2688.     {
  2689.         document.getElementById('SAFE-Combined-MoreInfo').collapsed = true;
  2690.         document.getElementById('SAFE-Combined-Settings').collapsed = true;
  2691.         document.getElementById('SAFE-Combined-WhiteList').collapsed = true;
  2692.         document.getElementById('SAFE-Combined-Enable').collapsed = true;
  2693.         document.getElementById('SAFE-Combined-Disable').collapsed = true;
  2694.         document.getElementById('SAFE-Combined-EnablePSurf').collapsed = true;
  2695.         document.getElementById('SAFE-Combined-DisablePSurf').collapsed = true;
  2696.         document.getElementById('SAFE-Combined-TellFriend').collapsed = true;
  2697.         document.getElementById('SAFE-Combined-SendFeedback').collapsed = true;
  2698.         document.getElementById('SAFE-Combined-Upsell').collapsed = true;
  2699.         //document.getElementById('SAFE-Combined-Help').collapsed = true;
  2700.         document.getElementById("SAFE-Combined-MS1").collapsed = true;
  2701.     }
  2702.     catch(e)
  2703.     {
  2704.     }
  2705. }
  2706.  
  2707. function registerNow()
  2708. {
  2709.     try
  2710.     {
  2711.         var interface = getSaXPCom();
  2712.         interface.LaunchRegister();
  2713.     }
  2714.     catch(e)
  2715.     {
  2716.     }
  2717. }
  2718.  
  2719. var stringBundleService = Components.classes["@mozilla.org/intl/stringbundle;1"].getService(Components.interfaces.nsIStringBundleService);
  2720. if (chromeExists("chrome://safe/content/oem.txt")) {
  2721.     OEMStrB = stringBundleService.createBundle("chrome://safe/content/oem.txt");
  2722. } else {
  2723.     OEMStrB = stringBundleService.createBundle("chrome://safe/content/default.txt");
  2724. }
  2725.  
  2726. if (!getUninstalled()) {
  2727.     mode = getMode();
  2728.     addUninstallObserver();
  2729.     if(mode!=CRIPPLED)
  2730.     {
  2731.         window.addEventListener("load", get_js, false);
  2732.         // window.addEventListener("load", pingDSS,false); causes hang due to Firefox proxy bug
  2733.         window.addEventListener("load", postInstallCheck, false);
  2734.         window.addEventListener("unload", cleanup, false);
  2735.     }
  2736. } else {
  2737.     var pref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
  2738.     pref.clearUserPref("extensions.safe.uninstalled");
  2739. }
  2740.  
  2741. whitelistedDomains = getWhitelist();
  2742.  
  2743. function getOSVersion()
  2744. {
  2745.     var OSName="Unknown OS";
  2746.     try
  2747.     {
  2748.         if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
  2749.         if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
  2750.         if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
  2751.         if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";
  2752.     }
  2753.     catch(e)
  2754.     {
  2755.     }
  2756.     return OSName;
  2757. }
  2758.  
  2759. function buildArgString()
  2760. {
  2761.     var argStr;
  2762.     argStr = "ref=safe&client_ver=" + getFullVersion();
  2763.     argStr = argStr + "&locale=" + getLocale();
  2764.     argStr = argStr + "&premium=" + getPremium();
  2765.     argStr = argStr + "&client_type=FF";
  2766.     argStr = argStr + "&aff_id=" + getAffid();
  2767.     //alert(argStr)
  2768.     return argStr;
  2769. }
  2770.  
  2771. function menuUpsell() {
  2772.     var url = getMenuUpsellUrl();
  2773.     if (url.match(/\?/))
  2774.         url = url + "&" + buildArgString();
  2775.     else
  2776.         url = url + "?" + buildArgString();
  2777.     if (url != null)
  2778.         window.open(url);
  2779.     else
  2780.         alert("no upsell url");
  2781. }
  2782.  
  2783. return {
  2784.     "getBuild": getBuild,
  2785.     "getVersion" : getVersion,
  2786.     "getAffid" : getAffid,
  2787.     "openSettings" : openSettings,
  2788.     "populateMenus" : populateMenus,
  2789.     "whitelist" : whitelist,
  2790.     "addWhitelist" : addWhitelist,
  2791.     "updateWhitelist" : updateWhitelist,
  2792.     "stripargs" : stripargs,
  2793.     "setEnable" : setEnable,
  2794.     "setPSurf" : setPSurf,
  2795.     "validatePassword" : validatePassword,
  2796.     "checkPassword" : checkPassword,
  2797.     "writeSettings" : writeSettings,
  2798.     "domain_specifier" : function() {return domain_specifier;},
  2799.     "upsell" : menuUpsell,
  2800.     "registerNow" : registerNow,    
  2801.     "getFullVersion" : getFullVersion,
  2802.     "getLocale" : getLocale,
  2803.     "getPremium" : getPremium,
  2804.     "getOSVersion" : getOSVersion,
  2805.     "buildArgString" : buildArgString,
  2806.     }
  2807. }
  2808.  
  2809. SiteAdvisorFunPack = SiteAdvisorFirefoxExtension();
  2810.